简体   繁体   中英

Django. How to connect drop-down list (from html) and forms?

A have a field in model (name model is Users_data):

bir_date = models.DateField(verbose_name="")

And form which represents model:

class Form_registration (ModelForm):
class Meta:
    model = Users_data

in html:

<form name="registration" method="post" action="save_data_user/">
{% csrf_token %}
{{ form_registration.as_p }}
<input type="submit" value="SignUp">
</form>

View which saves form:

def saves_data_user_on_registration (request):
if request.method == 'POST':
    c = {}
    c.update(csrf(request))
    form_user_data = Form_registration(request.POST, request.FILES)
    if form_user_data.is_valid():
        print form_user_data.errors
        form_user_data.save()
        return render_to_response('see_you_later.html', c,           context_instance=RequestContext(request))
    else:
        print form_user_data.errors
        return render_to_response('error.html', c, context_instance=RequestContext(request))

I can save simple data in form.

But I need save a data in drop-down list from html in field from my model Users_data.

<select name="DateOfBirth_Month">
<option>Month</option>
<option value="1">January</option>
<option value="2">February</option>
...



 <select id="cd-dropdown" class="cd-select">
 <option value="-1" selected>Day</option>
 <option value="1">01</option>
 <option value="2">02</option>
 ...

<select name="DateOfBirth_Year">
<option>Year</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
...

And I don't understand how I can to connect drop-down list with my form or model.

Thanks for answers.

You need to define a widget and set it for the DateField using widgets on the Meta class .

A good example of the particular widget that splits year, month and day into separate dropdowns can be found in Django documentation , see DateSelectorWidget :

class Form_registration (ModelForm):
    class Meta:
        model = Users_data
        widgets = {'bir_date': widgets.DateSelectorWidget()}

This code assumes you've created a widgets.py module with DateSelectorWidget class inside.

Another good widget for the task is django.forms.extras.widgets.SelectDateWidget :

Wrapper around three Select widgets: one each for month, day, and year.

Also see:

Hope that helps.

The answer is to use a choices attribute for your DateField in the model.

Here is how to do it: https://docs.djangoproject.com/en/dev/ref/models/fields/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM