Home > Mobile >  Django for loop template tag made using CBV
Django for loop template tag made using CBV

Time:04-09

I am trying to make a simple blog. One of my blog pages displays all of the blog posts on the website. I know I need to use a for loop but I do not know what to put in for the variables. All of the tutorials I have seen have used function-based views and I am using CBV. Help would be much appreciated.

all_posts.html

{% extends "base.html" %}
{% block content %}
<div >
  <h1>Blog Posts</h1>
</div>
<div >
 {% for  in  %}
   
 {% endfor %}
</div>
{% endblock %}

Views.py

from django.shortcuts import render
from django.views import generic
from . import models
from django.contrib.auth import get_user_model
User = get_user_model()
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.

class create_blog_post(generic.CreateView, LoginRequiredMixin):
    model = models.Blog_Post
    template_name = 'blog_app/creat_post.html'
    success_url = '/'
    fields = ('post_title', 'blog_content', 'files')

class view_blog_post(generic.ListView):
    model = models.Blog_Post
    template_name = 'view_post.html'
class delet_blog_post(generic.DeleteView, LoginRequiredMixin):
    model = models.Blog_Post
    template_name = 'delete_post.html'
class all_blog_posts(generic.ListView):
    model = models.Blog_Post
    template_name = 'all_posts.html'

modles.py

from django.db import models

# Create your models here.
class Blog_Post(models.Model):
    slug = models.SlugField(max_length=1000, editable=False, null=True)
    post_title = models.CharField(max_length=100, editable=True, blank=False, null=True)
    blog_content = models.TextField(max_length=10000, blank=False, editable=True, null=True)
    files = models.FileField(blank=True, null=True, upload_to=True)
    date = models.DateTimeField(blank=False, null=True, auto_now=True, editable=False)
    likes = models.IntegerField(blank=True, null=True, editable=False)

CodePudding user response:

As mentioned in the class-based generic views documentation

Well, if you’re dealing with a model object, this is already done for you. When you are dealing with an object or queryset, Django is able to populate the context using the lowercased version of the model class’ name. This is provided in addition to the default object_list entry, but contains exactly the same data, i.e. publisher_list.

So you'll probably have blog_post_list in addition to object_list. But, you can set the value of context_object_name to specify whatever you'd like it to be (just like how you specified template_name).

You can also check out the next section on overriding get_context_data() to add more things to the context dictionary.

  • Related