我的Django表单中有几个复选框。用户选择特定的复选框后,我想知道该用户选择了所有复选框。我可以在Django管理员中看到用户在填写表单时提供的名字,姓氏,用户名和电子邮件,但看不到用户选择了哪个复选框。
如何访问复选框的数据?我知道我需要为此在代码中进行一些修改,因此请在代码中建议我进行这些修改。我使用的是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})
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
return self.user.ngo
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库,因此我认为它们与该问题无关。
答案 0 :(得分:0)
您可以在视图中访问表单中的所有数据。 只需打印request.POST即可查看“ wichwich”复选框。