好的,所以我有django模型,并创建了该模型的一种形式。这是我的模板:
<form method="post" action="">{% csrf_token %}
{{ form.first_name }} {{form.last_name }} <br>
{{ form.username }} {{ form.password }} <br>
{{ form.date_of_birth_month }} {{ form.date_of_birth_day }} {{ form.date_of_birth_year }}
<input type="submit" value="Register"/>
</form>
{% for field, error in form.errors.items %}
{% if forloop.counter == 1 %}
{{ error | striptags }}
{% endif %}
{% endfor %}
现在,这是我的那种形式的模型。
class Users(models.Model):
months = (
('Month','Month'), ('January', 'January'), ('February','February'), ('March','March'), ('April','April'), ('May','May'), ('June','June'), ('July','July'), ('August','August'), ('September','September'), ('October','October'), ('November','November'), ('December','December'),
)
days = (
('Day', 'Day'), ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'),)
years = (
('Year','Year'), ('2013','2013'), ('2012','2012'), ('2011','2011'), ('2010','2010'), ('2009','2009'), ('2008','2008'),)
user_id = models.AutoField(unique=True, primary_key=True)
username = models.SlugField(max_length=50, unique=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
password = models.SlugField(max_length=50)
date_of_birth_month = models.CharField(verbose_name='', max_length=9, choices=months, default='Month')
date_of_birth_day = models.CharField(verbose_name='', max_length=3, choices=days, default='Day')
date_of_birth_year = models.CharField(verbose_name='', max_length=4, choices=years, default='Year')
现在,月份选项框的默认值为“月份”,用户名点击下拉列表并选择他出生的月份。日期和年份相同。但是,这使得Month,Day和Year成为用户可以选择的选项。如何让用户选择“月”作为月份,“日”作为日期或“年份”作为年份,然后提出错误消息“请选择有效的月/日/年”?
我的观点在这里:
def home_page(request):
form = UsersForm()
if request.method == "POST":
form = UsersForm(request.POST)
if form.is_valid():
form.save()
c = {}
c.update(csrf(request))
c.update({'form':form})
return render_to_response('home_page.html', c)
答案 0 :(得分:1)
为表单中的字段编写clean方法:
class UsersForm(form.Form):
# form fields here
def clean_month(self):
month = self.cleaned_data.get('month')
if month:
try:
month = int(month)
except:
raise forms.ValidationError('Invalid month')
if month < 1 or month > 12:
raise forms.ValidationError('Invalid month')
return month
对要验证的其他字段执行此操作。 Documentation
提供了更多帮助