如何在Django表单中添加复选框。

时间:2018-10-06 14:01:24

标签: database django-forms django-1.9

我想在Django表单中为不同的NGO(例如NGO1,NGO2等)添加复选框。我希望用户选择那些复选框,并且应该将数据保存在数据库中。

请,建议我对代码进行必要的更改。我正在使用Django 1.9。

models.py

from django.db import models
from django.contrib.auth.models import User

class UserProfileInfo(models.Model):

    user=models.OneToOneField(User)

    def __str__(self):
            return self.user.first_name
            return self.user.last_name
            return self.user.email

forms.py

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

class UserForm(forms.ModelForm):

class Meta():
    model = User
    fields = ('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():

        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})

admin.py

from django.contrib import admin
from volunteer.models import UserProfileInfo

# Register your models here.
admin.site.register(UserProfileInfo)

urls.py

from django.conf.urls import url

from . import views

app_name = 'volunteer'

urlpatterns = [

 url(r'^', views.register, name='register'),
]

volunteer.html(具有表单)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">


<meta name="viewport" content = "width=device-width, initial-scale=1.0">


</head>      

<body>   

 <div class="jumbotron">
    {% if registered %}
       <p>Thank you  <p>

    {% else %}
      <h1>Register yourself for Volunteering</h1>




 <form method="post">
    {% csrf_token %}
    {{ user_form.as_p }}
 <input type="submit" name="" value="Register as a Volunteer">

 {% endif %}

 </div> 


 </form>

</body>
</html> 

注意-由于格式问题,我没有在上述html代码中包含bootstrap,ajax和JQuery库,我认为与该问题无关。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用Django形式的checkbox widget轻松实现这一目标。

将表单类定义为:

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')

现在,在保存数据的同时,您可以在

中访问复选框的数据。
if request.method =="POST" :
    user_form = UserForm(data=request.POST)

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

        registered = True

    else:
        print(user_form.errors)

else:
    user_form = UserForm()

希望有帮助。