Is there a way of passing a model into a template without a class based view

My question is can I use a function view to pass in a model inside my template to be iterated through. This is how my model looks like

class Listing(models.Model):
    user = models.ForeignKey( User, on_delete=models.CASCADE)

    itempicture = models.ImageField(upload_to="images",blank=False)

    title = models.CharField(max_length=50)

    about = models.CharField(max_length=500)


    published_date = models.DateTimeField(blank=True, null=True)

how can I write a function based view to pass in my database just like a class based (list view)

You can simply use all() but if you want custom filtered queryset which we usually do by overriding get_queryset() method in ListView so you can use filter() method in the following way:

def home(request):
    listings=Listing.objects.all() #Give the default queryset as ListView
    filtered_listings=Listing.objects.filter(user=request.user) #Give the queryset for current logged in user which can be achieved by overriding "get_queryset()" method in "ListView".

    return render(request,"some_folder_name/some_filename.html",{'listings': listings})

Then you can simply iterate any of the queryset in template (Assuming, you know the logic of and template file).

Back to Top