好的,所以我有 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')
现在,月份选择框的默认值为“月份”,用户名单击下拉菜单并选择他出生的月份。日和年也是如此。然而,这使得月、日和年成为用户可以选择的选项。我怎样才能做到这一点,如果用户选择“月”作为月份,“日”作为日或“年”作为年,然后引发错误消息说“请选择有效的月/日/年”?
我的观点在这里:
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)