0
我的表單設置正常並且沒有任何錯誤,但是在添加了一個帶有RadioSelect小部件的IntegerFIeld後,表單不再驗證。 (在此之前,我只有模型中的CharFields,沒有小工具)添加IntegerField和Radio Widget之後,Django表單驗證不起作用
我已經搜索了其他類似的問題,但一直沒能找到任何解決此問題的方法。
目前我只是不斷收到我在views.py中編碼的錯誤消息。
我的設立如下:
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.utils import timezone
from .forms import DiaryEntryForm
from .models import DiaryEntry
def new_entry(request):
if request.method == "POST":
form = DiaryEntryForm(request.POST)
if form.is_valid():
entry = form.save(commit=False)
entry.author = request.user
entry.created_date = timezone.now()
entry.save()
messages.success(request, "Entry created successfully")
return redirect(entry_detail, entry.pk)
else:
messages.error(request, "There was an error saving your entry")
return render(request, 'diaryentryform.html', {'form': form})
else:
form = DiaryEntryForm()
return render(request, 'diaryentryform.html', {'form': form})
forms.py
from django import forms
from .models import DiaryEntry, FORM_CHOICES
class DiaryEntryForm(forms.ModelForm):
body = forms.ChoiceField(widget=forms.RadioSelect(),choices=FORM_CHOICES)
mind = forms.ChoiceField(widget=forms.RadioSelect(),choices=FORM_CHOICES)
class Meta:
model = DiaryEntry
fields = ('body', 'mind', 'insights')
models.py
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.conf import settings
from django import forms
# Create your models here.
FORM_CHOICES = [
('very bad', 'very bad'),
('bd', 'bad'),
('OK', 'OK'),
('good', 'good'),
('very good', 'very good'),
]
class DiaryEntry(models.Model):
"""
Define the diary entry model here
"""
author = models.ForeignKey(settings.AUTH_USER_MODEL) # link author to the registered user
title = models.CharField(max_length=200) # set this to be the date later on
created_date = models.DateTimeField(auto_now_add=True)
body = models.IntegerField(blank=True, null=True, choices=FORM_CHOICES)
mind = models.IntegerField(blank=True, null=True, choices=FORM_CHOICES)
insights = models.TextField()
def publish(self):
self.save()
def __unicode__(self):
return self.title
非常感謝提前。
那麼,你期望什麼?一個'IntegerField'需要一個整數。你的選擇是字符串。你需要在你的模型中使用一個CharField。 – dirkgroten
當然!多麼愚蠢的錯誤!十分感謝你的幫助。 –
並學習如何使用調試器:當您可以真正看到您的表單發佈的內容時,解決這類問題就容易得多了... – dirkgroten