自动填充表单字段 django

Auto populated form fields django

我正在开发我的博客应用程序,现在我添加了评论部分我想在 forms.But 中自动填充两个字段我收到错误 NOT NULL 约束失败:MainSite_comment.user_id
Models.py

class Comment(models.Model):
    comment_text = models.TextField(("comment_text"))
    user = models.ForeignKey("account.User", related_name=("comment_user"), on_delete=models.CASCADE)
    #post = models.ForeignKey("Post", related_name=("comment_post"), on_delete=models.CASCADE)
    parent = models.ForeignKey('self',related_name=("replies"), on_delete = models.CASCADE , blank= True ,null=True)
    timestamp = models.DateTimeField(("Comment Timestamp"), auto_now=False, auto_now_add=True)

    def __str__(self):
        return self.user.username

Forms.py

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields =['comment_text']

        labels ={
            'comment_text':'',
        }

        widgets ={
            'comment_text': forms.Textarea(attrs = {'class':'form-control','rows':'5','cols':'50',
                'style' : 'background: #fff;',
                'placeholder':'Write a comment....'}),
            
        }

Views.py

class PostDetailView(FormMixin,DetailView):
    model = Post
    form_class = CommentForm
    template_name = 'MainSite/blogpost.html'
    
    def form_valid(self, form):
        form.instance.user_id = self.request.user.id
        return super().form_valid(form)

    def post(self,request,slug):
        print(request.user.id)
        if request.method == 'POST':
            form = CommentForm(request.POST)
            if form.is_valid():
                form.save()
                messages.success(request,"Comment added successfully")

    success_url = reverse_lazy('home')

我想自动填充用户和 post 字段(稍后我将更改模型中的 post 字段)。我在 model.Currently 中自动填充用户字段时出错,我使用在 url 中插入以显示 post.I 不知道这个 form_valid() 是如何工作的,它有什么作用 returns 以及这个 实例 是什么。

感谢您的帮助,任何建议都有帮助。

你应该调用 form_valid 方法,否则在那里设置用户是没有意义的,所以:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy

class PostDetailView(LoginRequiredMixin, FormMixin, DetailView):
    model = Post
    form_class = CommentForm
    template_name = 'MainSite/blogpost.html'
    success_url = reverse_lazy('home')
    
    def form_valid(self, form):
        form.instance.user_id = self.request.user.id
        form.save()
        messages.success(self.request, 'Comment added successfully')
        return super().form_valid(form)

    def post(self, request, slug):
        form = self.get_form()
        self.object = self.get_object()
        if form.is_valid():
            self.<strong>form_valid(form)</strong>
        else:
            self.<strong>form_invalid(form)</strong>