Django:在用户通过身份验证后创建评论表单

时间:2018-04-21 05:45:00

标签: python django django-models django-forms django-templates

我正在创建一个简单的博客应用程序。用户登录此应用程序,而他/她可以在我的博客应用程序上发表评论。但是无法实现这个想法。 这是我的models.py文件

from django.db import models

# Create your models here.

from user.models import CustomUser

from django.conf import settings
from django.db import models
from django.urls import reverse

class BlogPost(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    blog_title=models.CharField(max_length=200)
    blog_description=models.TextField()
    blog_pub=models.DateTimeField(auto_now_add=True)
    blog_update=models.DateTimeField(auto_now=True)


    def __str__(self):
        return self.blog_title


    def get_absolute_url(self):

        return reverse('blog:blog_post', kwargs={'pk': self.pk})




class Comment(models.Model):
    blogpost=models.ForeignKey(BlogPost, on_delete=models.CASCADE)
    comment=models.CharField(max_length=300)
    author=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,blank=True, null=True)
    author_name = models.CharField(max_length=50, default='anonymous', verbose_name=("user name"))
    comment_pub = models.DateTimeField(auto_now_add=True)

    comment_update = models.DateTimeField(auto_now=True)

    def get_absolute_url(self):
        return reverse('blog:home', kwargs={'pk':self.pk})

    def __str__(self):
        return self.comment

这是views.py文件

class BlogPostSingle(DetailView, FormView):
    model=BlogPost
    template_name='blog/blog_post_single.html'
    #fields = ['blog_title']
    form_class = CreateCommentForm
    success_url = '/blog/'

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

这是我的forms.py文件

class CreateCommentForm(ModelForm):
    class Meta:
        model=Comment
        fields = ('comment', 'blogpost')

这是我的html文件和表单部分

{% if user.is_authenticated %}
        <h5>Hi, {{user.name}} leave your comment now</h5>
        <form action="" method="post">
            {% csrf_token %} {{form.as_p}}

            <input type="submit" value="Submit comment">
        </form>
        {% else %}
        <p>You're not logged in this site, please  <a href="{% url 'login' %}">log</a> in for comment </p>
        {% endif %}

我的目标想法只是用户登录我的博客应用程序。他可以在我的博客应用程序上评论任何帖子。我的评论模型包含两个forignkey字段。

1 个答案:

答案 0 :(得分:0)

您应该将用户传递到您的观看环境,因此它将在模板中提供:

class BlogPostSingle(DetailView, FormView):
    ...
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['user'] = self.request.user
        return context
<{1>} get_context_datahttps://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-display/#detailview

self.request上看到 https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/#dynamic-filtering