dimanche 7 octobre 2018

How to access the checkbox data in Django form

I have a few checkboxes in my Django form. After a user selects a particular checkbox, I want to know which all checkboxes were selected by the user. I can see the first name, last name, username, and email of the user in the Django admin, that the user provides while filling up the form, but I can't see which checkboxes did the user select.

How can I access the Checkbox's data? I know I need to do some modifications in my code for that, so please suggest me the modifications in my code. I'm using Django 1.9.

forms.py

from django import forms
from django.contrib.auth.models import User
from volunteer.models import UserProfileInfo

NGO_CHOICES = (
('one', 'ONE'),
('two', 'TWO'),
('three', 'THREE'),)

class UserForm(forms.ModelForm):
ngo = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, 
choices=NGO_CHOICES)

class Meta():
    model = User
    fields = ('ngo','email','first_name','last_name','username')

views.py

from django.shortcuts import render
from volunteer.forms import UserForm



def register(request):

registered = False

if request.method =="POST" :
    user_form = UserForm(data=request.POST)

    if user_form.is_valid():
        ngo = user_form.cleaned_data['ngo'] #getting the list of the ngos. 

        user = user_form.save()

        user.save()

        registered = True

    else:
        print(user_form.errors)

else:
    user_form = UserForm()

return render(request, 'volunteer/volunteer.html',
                         {'user_form':user_form,
                          'registered':registered})

NOTE - I haven't included bootstrap, ajax and jquery libraries in the above HTML code, I don't think they have anything to do with the problem, so.




Aucun commentaire:

Enregistrer un commentaire