【问题标题】:Comment Form not posting on submit in django评论表未在 django 中提交时发布
【发布时间】:2020-05-01 06:09:07
【问题描述】:

我正在开发一个博客站点,评论的提交表单意外重定向到/post

错误/输出: 在点击提交之前

  <WSGIRequest: GET '/post/2'>        -# my print statement in views.py
  fail                                -# my print statement in views.py
  [01/May/2020 11:28:43] "GET /post/2 HTTP/1.1" 200 14275

点击提交

Not Found: /post/
[2020-05-01 11:33:39,126] log: WARNING - Not Found: /post/
[01/May/2020 11:33:39] "POST /post/ HTTP/1.1" 404 2795

提交按钮是提交类型,这里是与它相关的所有内容,我已经坚持了一段时间了。我在 views.py 中添加了 print() 来找出问题所在。帮助将不胜感激

post.html

<form method="POST" action="." class="commenting-form">
                    {% csrf_token %}
                    <div class="row">
                      <div class="form-group col-md-12">
                        {{ form }}
                      </div>
                      <div class="form-group col-md-12">
                        <button type="submit" class="btn btn-secondary">Submit Comment</button>
                      </div>
                    </div>
</form>

views.py

def postview(request, my_id):
    most_recent = Posts.objects.order_by('-timestamp')[:3]
    category_count = get_category_count()
    post = get_object_or_404(Posts, id=my_id)

    form = CommentForm(request.POST or None)
    print(request)

    if request.method == "POST":
        print(form)
        if form.is_valid():
            form.instance.user = request.user
            form.instance.post = post
            form.save()
            print(form)
            return redirect(reverse('postdetail', kwargs={
                'my_id': post.pk
            }))
    else:
        print('fail')

    context = {
        'post': post,
        'most_recent': most_recent,
        'cat_count': category_count,
        'form': form
    }
    return render(request, 'post.html', context)

models.py

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    content = models.TextField()
    post = models.ForeignKey(
        'Post', related_name='comments', on_delete=models.CASCADE)

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

forms.py

class CommentForm(forms.ModelForm):
    content = forms.CharField(widget=forms.Textarea(attrs={
        'class': 'form-control',
        'placeholder': 'Type your comment',
        'id': 'usercomment',
        'rows': '4'
    }))
    class Meta:
        model = Comments
        fields = ('content', )

【问题讨论】:

    标签: django forms django-models


    【解决方案1】:

    在表单标签,属性动作中,使用".",使用""(空字符串)

    这是sn-p

    <form action=""></form>
    

    或者在action属性中使用绝对路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 2021-12-29
      • 2011-05-17
      • 2019-01-09
      相关资源
      最近更新 更多