2017-10-09 55 views
0

我正在使用Django自定義窗體: 我調試過那個form.is_valid函數沒有運行,即使所有的數據都進入了視圖。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> 

請幫助我! 在此先感謝!

回答

1

試試:

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) 

需要ATTR添加valueradio

<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> 
                    <!-- ^^^^^^^^^^ --> 
+0

嗨,@Bear!它返回目標錯誤! –

+0

您的表單有錯誤,我更新了答案,您可以試試 –

+0

我認爲這是category_fit radio選項的錯誤,我如何在我的模板中使用這個單選按鈕?請! –

1

調用form.is_valid(後),調用form.errors和打印,要知道預期輸入到表單。

form.is_valid() 
print(form.errors) 

from django.http import HttpResponse 

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

HttpResponse return category_fit! –

+0

這意味着category_fit字段存在一些問題,而獲取表單數據 –

+0

是否必須在「category_fit」中添加一些屬性:forms.RadioSelect()在我的forms.py中? –