Django表单不运行form.is_valid

时间:2017-10-09 06:23:34

标签: python django forms django-forms django-views

我正在使用Django自定义表单: 我调试了form.is_valid函数没有运行,即使视图中都有所有数据。

models.py

choices = (
   ('yes', 'Yes'),
   ('no', 'No'),
   ('not sure', 'Not Sure'),
)
class TaggedArticle(models.Model):
   user = models.ForeignKey(User, related_name='tagging')
   category_fit = models.CharField(choices=choices, max_length=255)
   article = models.ForeignKey(Article, related_name='articles')
   relevant_feedback = models.TextField(blank=True)
   created_at = models.DateTimeField(default=timezone.now, editable=False)

forms.py

class TagForm(forms.ModelForm):
    class Meta:
        model = TaggedArticle
        fields = ('user', 'category_fit', 'article', 'relevant_feedback')
        widgets = {
            'category_fit': forms.RadioSelect()
        }

views.py

def post(self, request, *args, **kwargs):
    if request.method == 'POST':
        post_data = request.POST.copy()
        post_data.update({'user': request.user.pk})
        form = forms.TagForm(post_data)
        print('request recieved')
        if form.is_valid():
            tag = TaggedArticle()
            tag.user = request.user
            article = Article.objects.all().filter(id=form.cleaned_data['article'])
            tag.category_fit = form.cleaned_data['category_fit']
            tag.article = article
            tag.relevant_feedback = form.cleaned_data['relevant_feedback']
            tag.save()

        return HttpResponse('Tagged Successfully!', status=200)

更新 我认为它的单选按钮错误: 以下是我从模板中获取此信息的方法:

<td><label class="radio-inline"><input type="radio" name="category_fit">Yes</label></td>
<td><label class="radio-inline"><input type="radio" name="category_fit">No</label></td>
<td><label class="radio-inline"><input type="radio" name="category_fit">Not Sure</label>

请帮帮我! 提前谢谢!

2 个答案:

答案 0 :(得分:2)

试一试:

    if form.is_valid():
        tag = form.save(commit=False)
        tag.user = request.user
        tag.save()
   else:
        # Added else statment
        msg = 'Errors: %s' % form.errors.as_text()
        return HttpResponse(msg, status=400)

您需要将value attr添加到radio

<td><label class="radio-inline"><input type="radio" name="category_fit" value="yes">Yes</label></td>
<td><label class="radio-inline"><input type="radio" name="category_fit" value="no">No</label></td>
<td><label class="radio-inline"><input type="radio" name="category_fit" value="not sure">Not Sure</label>
                                                                     <!-- ^^^^^^^^^^  -->

答案 1 :(得分:1)

在调用form.is_valid()之后,调用form.errors并打印它以了解表单的预期输入。

form.is_valid()
print(form.errors)

from django.http import HttpResponse

form.is_valid()
return HttpResponse(form.errors)