django 如何在CBV中创建评论表单?

omjgkv6w  于 2023-01-06  发布在  Go
关注(0)|答案(2)|浏览(130)

我创建了一个模型评论,它很容易显示评论在后的底部,但我应该如何使一个表单添加评论在同一页作为art_detail.我的意思是我必须使用CreateView,但ArtDetailView()使用DetailView,所以我不能把两个在一个视图,当我把他们我分开的视图只有一个视图发送数据到模板模型:

class Comment(models.Model):
    writer = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)
    art = models.ForeignKey(Art,on_delete=models.CASCADE)
    text = models.TextField(max_length=500)
    date = models.DateTimeField(auto_now_add=True)

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

视图:

class CommentView(CreateView):
    model = Comment
    template_name = 'art_detail.html'
    fields = ['text']

    def form_valid(self, form):
        form.instance.art = Art.objects.get(id=self.id)
        form.instance.writer = self.request.user
        return super().form_valid(form)

class ArtDetailView(DetailView):
    model = Art
    template_name = 'art_detail.html'

处理这个评论idk即使我需要一个url或没有?你能请帮助这个问题吗

7xllpg7q

7xllpg7q1#

您可以创建一个表单,并通过混合这两种视图来使用它,如下所示:

class ArtDetailView(FormView, DetailView):
    model = Art
    form_class = CommentForm

    def get_context_data(self, **kwargs):
        context = super(ArtDetailView, self).get_context_data(**kwargs)
        context['form'] = self.get_form()
        return context

    def post(self, request, *args, **kwargs):
        return FormView.post(self, request, *args, **kwargs)
bkhjykvo

bkhjykvo2#

CBV和FBV可以达到相同的效果,但是在FBV中查看它们比在CBV中查看它们更能帮助您理解视图。下面是如何在FBV中应用此功能的示例:
views.py

def post(request, pk):
    form = CommentForm()
    post = Post.objects.get(id=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.cleaned_data['comment']
            comment = form.save(commit=False)
            comment.post = post
            comment.save()

            return redirect('post_page', id=post.pk)
        else:
            return render(request, 'post_page.html', {'post': post, 'form':form})
    return render(request, 'post_page.html', {'post': post, 'form':form})

models.py

class Post(models.Model):
    post_title = models.CharField(max_length=200, null=True, blank=True)
    post_description = models.CharField(max_length=200, null=True, blank=True)
    post_complete = models.TextField(max_length=2000, null=True, blank=True)

class Comment(models.Model):
    comment = models.CharField(null=True, blank=False, max_length=500, verbose_name="Comment")
    commentor = models.CharField(max_length=50)
    post_related = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE, null=True)

forms.py

class CommentForm(forms.ModelForm):

    commentor = forms.CharField(max_length = 40, label = False, required = True,error_messages={'required': 'Name is required'},
    widget=forms.TextInput(attrs={
        'oninvalid': "this.setCustomValidity('Name is required')",
        'onchange': "this.setCustomValidity('')",
        'class': 'form-control', 'placeholder': 'Name:'}))

    comment = forms.CharField(max_length = 500, label = False, required = True,error_messages={'required': 'Comment is required'},
    widget=forms.Textarea(attrs={
        'oninvalid': "this.setCustomValidity('Comment is required')",
        'onchange': "this.setCustomValidity('')",
        'class': 'form-control', 'placeholder': 'Comment:'}))

    class Meta:
        model = Comment
        fields = ['name','comment']

post_page. html(包含帖子和相关评论的页面)

{{post.title}}
{{post.description}}
{{post.complete}}



{% for comment in post.comments.all %}
{{comment.commentor}}
{{comment.comment}}
{% endfor %}

urls.py

path('post_page/<pk>/', views.post, name='post_page'),

When linking to the post, make sure to add post.pk in href
希望这能帮上忙

相关问题