
[英]How to create radio buttons in django which fields use in form and model
[英]how to create a dynamically-created radio buttons form in django
你好 。
我是django的新手,我想在html中创建一个看起来像上图的表单。 当用户选择单选按钮时,表单应保存数据。
如何在django中实现这样一个表单(请注意用户不能选择多个答案)
您想使用ChoiceField和RadioSelect :
from django import forms
class GenderForm(forms.Form):
CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
choice = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())
请记住, Django文档是你的朋友 !
动态更改选择如果您希望能够动态创建表单,那么使用ModelForm而不是forms.Form可能是个好主意。 这是一个例子:
from django.db import models
from django.forms import ModelForm
from django import forms
class Answer(models.Model):
answer = models.CharField(max_length=100)
def __unicode__(self):
return self.answer
class Question(models.Model):
title = models.CharField(max_length=100)
answers = models.ManyToManyField('Answer')
class QuestionForm(ModelForm):
class Meta:
model = Question
fields = ('title', 'answers')
widgets = {
'answers': forms.RadioSelect(),
}
在您的视图中,使用指定要使用的实例实例化表单:
question = Question.objects.order_by('?')[0]
form = QuestionForm(instance=question)
然后,表单将使用与该问题相关的答案(在这种情况下是随机选择的)并像往常一样将表单传递给模板上下文。
这里有一个很好的例子: https : //code.djangoproject.com/wiki/CookBookNewFormsDynamicFields
基本上,您的表单代码将遵循以下模式:
from django import forms
class MyForm(forms.Form):
static_field_a = forms.CharField(max_length=32)
static_field_b = forms.CharField(max_length=32)
static_field_c = forms.CharField(max_length=32)
def __init__(self, dynamic_field_names, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
for field_name in dynamic_field_names:
self.fields[field_name] = forms.CharField(max_legth=32) # creates a dynamic field
用法示例:
>>> dynamic_fields = ('first_name', 'last_name', 'company', 'title')
>>> my_form = MyForm(dynamic_field_names=dynamic_fields)
>>> my_form.as_ul()
u'<li><label for="id_static_field_a">Static field a:</label> <input id="id_static_field_a" type="text" name="static_field_a" maxlength="32" /></li>\n<li><label for="id_static_field_b">Static field b:</label> <input id="id_static_field_b" type="text" name="static_field_b" maxlength="32" /></li>\n<li><label for="id_static_field_c">Static field c:</label> <input id="id_static_field_c" type="text" name="static_field_c" maxlength="32" /></li>\n<li><label for="id_first_name">First name:</label> <input id="id_first_name" type="text" name="first_name" maxlength="32" /></li>\n<li><label for="id_last_name">Last name:</label> <input id="id_last_name" type="text" name="last_name" maxlength="32" /></li>\n<li><label for="id_company">Company:</label> <input id="id_company" type="text" name="company" maxlength="32" /></li>\n<li><label for="id_title">Title:</label> <input id="id_title" type="text" name="title" maxlength="32" /></li>
这将呈现带有以下文本输入的表单:
只需使用forms.ChoiceField()
或任何你想要的,而不是forms.TextField()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.