I have a Django application and want to display multiple choice checkboxes in a user's profile. They will then be able to select multiple items.
But I am not able to save the form that is created. Can anyone help?
My models.py looks like this:
class multiChoice(models.Model):
user=models.ForeignKey(User)
Options = (
("AUT", "Australia"),
("DEU", "Germany"),
("NLD", "Neitherlands")
)
Countries = models.ManyToManyField(Choices,choices=Options)
User.multiChoice=property(lambda u:multiChoice.objects.get_or_create(user=u)[0])
forms.py:
class multiChoiceForm(forms.Form):
Countries = forms.ModelMultipleChoiceField(queryset=Choices.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
class Meta:
model=multiChoice
fields=("Countries")
views.py:
def multiChoice_v1(request):
args = {}
args.update(csrf(request))
if request.method == 'POST':
form = multiChoiceForm(request.POST)
if form.is_valid():
countries = form.cleaned_data.get('countries')
countries.save()
form.save_m2m()
return HttpResponseRedirect('/accounts/loggedin/')
else:
form=multiChoiceForm()
args={}
args.update(csrf(request))
args['form']=form
return render_to_response('editprofile_v2.html', args)
urls.py - snippet of the multi-choice view alone:
url(r'^accounts/profile_v2/$', 'guitarclubapp.views.multiChoice_v1'),
editprofile_v2.html:
<html>
<form method='post'>{% csrf_token %}
<label> Countries </label>
<select name="Countries" id="Countries" class="multiselect" multiple="multiple">
<option value="AUT" selected="selected">Austria</option>
<option value="DEU" selected="selected">Germany</option>
<option value="NLD" selected="selected">Netherlands</option>
</select>
<input type='submit' value='submit'>
</form>
</html>
Is there anything that I am missing out (or) have done anything wrong?
Should I change the way I am defining my model?
Any help or references would be greatly appreciated.
Thanks in advance.