简体   繁体   中英

Using ModelChoiceField and queryset argument using Django

I want to create a simple html <select> list.

In models.py I define a Member model that has numerous details about each User . One detail is a year, ie 2000, 2001, etc. In a member registration form I want a <select> list with years to choose from that goes back 20 years (changes dynamically as years go by).

I have learned from this post that I should use ModelChoiceField with a queryset argument.

It seems that I need to create another model dedicated to the dynamic list but I don't think that is correct because it really doesn't need to be in a database as it can be calculated each time the form is loaded.

So what should I put in the queryset attribute? Ideally, I want to create simple function that obtains the current year creates some type of array that is the queryset. I am not that experienced with python so this may be a dumb question.

RESPONSE TO Daniel Roseman:

Yes, that makes much more sense. Thanks! However, I did have to modify the datetime line to be:

import datetime
year = datetime.date.today().year

You've misunderstood the answer to that question, or maybe my comment on that answer. You would only use a ModelChoiceField if the choice needs to get its values from a model - my comment was only to point out that you can do that whether or not the form itself is based on a model. But in your case, the choice has nothing to do with any model, so ModelChoiceField is the wrong option.

A standard ChoiceField is the way to go here:

class MemberRegistrationForm(forms.ModelForm):
    year = forms.ChoiceField(choices=[])

    def __init__(self, *args, **kwargs):
        super(MemberRegistrationForm, self).__init__(*args, **kwargs)
        year = datetime.datetime.now().year
        self.fields['year'].choices = [(i, i) for i in range(year-20, year+1)]

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