Problem in django ChoiceField
I have come across a problem when I submit an empty radio input. If I select a choice, the form functions fine; however, if I leave it blank, I get the following error --
MultiValueDictKeyError at /
Key 'like' not found in <QueryDict:...
I've tried several solutions, including using a dict.get on the mentioned 开发者_如何学运维field 'like' and deleting the column in the database -- it seems to be a problem in the forms module.
Here is my code:
In forms.py --
from django import forms
class PictureForm(forms.Form):
like = forms.ChoiceField(widget=forms.RadioSelect(), choices=(
[('yes','yes'), ('no','no'),]),)
name = forms.CharField()
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
And in views.py
def index2(request):
if request.method == 'POST':
form = PictureForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
Picture.objects.create(like=cd['like'], name=cd['name'], email=cd['email'], message=cd['message'])
return HttpResponseRedirect ('/thanks/')
else:
form = PictureForm()
return render_to_response('index2.html', {'form':form}, context_instance=RequestContext(request))
I would like to have it so there is obviously no error when the radio submitted blank -- and
1) how to allow a blank submission, and
2) how to prompt an error message.
In addition, the validations are not working on this form (I've done previous tutorials, and this is the first time the validations aren't automatically working).
Thank you.
Picture.objects.create(like=cd['like'], [...])
You are trying to access the cd dictionary with a key that doesn't exist, since the field has no value.
Try putting in an if/else statement:
if like in cd:
Picture.objects.create(like=cd['like'], [...])
Also, it's not clear if you're using a ModelForm as Thierry suggested, but if so, you might need to add the parameters blank=True, null=True to your Model field creation, in order to allow for null values.
What does your Picture model look like? Does your model have any restrictions on the uniqueness of multiple columns? It looks like you are using your form to create a model, did you read the doc on ModelForm?
Your form can be simplified to:
from django.forms import ModelForm
class PictureForm(ModelForm):
like = forms.ChoiceField(widget=forms.RadioSelect(), choices=(
[('yes','yes'), ('no','no'),]),)
class Meta:
model = Picture
In your view:
if form.is_valid():
form.save()
精彩评论