【问题标题】:Reason for form not showing although I added it in the template尽管我在模板中添加了表单但未显示的原因
【发布时间】:2020-11-12 02:50:17
【问题描述】:

我在我的 Django 项目中创建了一个新的评论模型,但尽管我在模板中添加了表单,但表单没有显示在浏览器中。

这是models.py

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    body = models.TextField(max_length=300)

    def __str__(self):
        return str(self.pk)

以下是观点:

def comment_create(request, self):
    post = get_object_or_404(Post, slug=self.kwargs['slug'])
    user = User.objects.get(user=request.user)

    c_form = CommentModelForm()

    context = {
        'post': post,
        'user': user,
        'c_form': c_form,
    }
    return context

这是forms.py

class CommentModelForm(forms.ModelForm):
    body = forms.CharField(label='',
                            widget=forms.TextInput(attrs={'placeholder': 'Add a comment...'}))
    class Meta:
        model = Comment
        fields = ('body',)

这里是 urls.py

    path('blogs/comment', comment_create, name='comment-post'),

这是模板:

                <form action="" method="POST"class='ui fluid form'>
                    {% csrf_token %}
                    <input type="hidden" name="post_id" value={{post.id}}>
                      {{ c_form }}
                    <button type="submit" name="submit_c_form" class="">Send</button>
                </form>

【问题讨论】:

    标签: python django django-forms


    【解决方案1】:

    首先,您必须获取请求的类型,我为 GET 和 POST 请求添加了 if/else。添加了 form.is_valid 检查。

    在您的函数中,您试图从 url 中获取一个 kwarg,但您的路径中没有 kwarg。

    path('blogs/<slug:slug>/comment', comment_create, name='comment-post'),
    

    views.py

    def comment_create(request, self):
        post = get_object_or_404(Post, slug=self.kwargs['slug'])
    
        if request.method == 'POST': # If user submitted form
            c_form = CommentModelForm(request.POST) # Get form response
            if c_form.is_valid(): # Chekc if form is valid
                c_form.user = User.objects.get(user=request.user) # Get user and add it to form
                c_form.post = post # Add post to form
                c_form.save() # Save form
        else:
            c_form = CommentModelForm() # Pass form
    
        context = {
            'post': post,
            'c_form': c_form,
        }
        return render(request, 'app/comment.html', context) # change template
    

    forms.py

    class Meta:
            model = Comment
            fields = ['body'] # When I set tuples it normally gives me an error
    

    【讨论】:

    • 它仍然没有显示,在管理员中制作的 cmets 正在显示,但我无法从浏览器提交。没有表格显示
    • 我对代码进行了一些重大更改。您只需将 slug 从您的 Post 视图传递到 Comment 创建视图,它应该可以工作。 @A_K
    猜你喜欢
    • 2019-02-19
    • 2019-08-07
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2018-07-22
    • 2020-10-17
    • 2022-07-22
    • 2012-05-16
    相关资源
    最近更新 更多