Home > Enterprise >  Tell me how to transfer this code from Html to models
Tell me how to transfer this code from Html to models

Time:12-24

There is a code in html {{post.author.posts.count}} that counts the number of posts by the author. I have such a question, how to transfer it to views.py

def post_detail(request, post_id):
post = get_object_or_404(Post, id=post_id)
context = {
    'post': post,
}
return render(request, 'posts/post_detail.html', context)

class model

class Post(models.Model):
text = models.TextField(verbose_name='Текст')
pub_date = models.DateTimeField(
    auto_now_add=True,
    verbose_name='Дата публикации'
)
group = models.ForeignKey(
    Group,
    on_delete=models.SET_NULL,
    blank=True,
    null=True,
    related_name='posts',
    verbose_name='Группа',
)
author = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    related_name='posts',
    verbose_name='Автор',
)

def __str__(self):
    return self.text

I need to find an existing post, find its author and sort all posts by this author and calculate the total number of posts

CodePudding user response:

You can not pass values form HTML to views in Django, but you can create @property to count all posts of the specific author.

you can try like this

models.py

class Post(models.Model):
    text = models.TextField(verbose_name='Текст')
    pub_date = models.DateTimeField(
        auto_now_add=True,
        verbose_name='Дата публикации'
    )
    group = models.ForeignKey(
        Group,
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        related_name='posts',
        verbose_name='Группа',
    )
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='posts',
        verbose_name='Автор',
    )

    def __str__(self):
        return self.text

views.py

def Demoview(request,post_id):
    get_post = Post.object.get(id=post_id)
    author_of_post = get_post.author 
    all_post_of_author= Post.object.filter(author__id=get_blog.author.id)
    count_all_post_of_author= Post.object.filter(author__id=get_blog.author.id).count()

    context = {

        'author_of_post':author_of_post,
        'all_post_of_author':all_post_of_author,
        'count_all_post_of_author':count_all_post_of_author,
    }

    return render(request,'post.html',context)

CodePudding user response:

Happened. Here is the code that came out.

def post_detail(request, post_id):
post = get_object_or_404(Post, id=post_id)
author = post.author
post_count = Post.objects.filter(author=author).count()
context = {
    'author': author,
    'post_count': post_count,
    'post': post,
}
return render(request, 'posts/post_detail.html', context)
  • Related