[Answer]-How to write view from ModelChoiceField response?

0👍

You may change the value of option by adding to_field_name='year' to the choice ModelChoicefield in the form.

So you’ll get

<option value="1981">1981</option>
<option value="1982">1982</option>
<option value="1983">1983</option>
👤Nav

1👍

It looks like you’re mixing forms.Form and forms.ModelForm in class season_choice based on your use of forms.Form but also declaring a Meta class.

If you need a different form widget than the model default, you can over ride it in the Meta class if using a ModelForm. When using ModelForms it’s best practice to explicitly list the fields to be displayed so that future fields (potentially sensitive ones) are not added by default.

class SeasonForm(forms.ModelForm):
    class Meta:
        model = Season
        fields = ['year']
        widgets = {
            'year': forms.widgets.Select(),
        }

Django models also have a Meta class that will allow you to provide a default ordering:

class Season(models.Model):
    year = ...

    class Meta:
        ordering = ['-year']

If you don’t want the entire Model class to have that ordering, you can either change this in your view or create a proxy model, then in your form use model = SeasonYearOrdering.

class SeasonYearOrdering(Season):
    class Meta:
        ordering = ['-year']
        proxy = True

Another item of interest is the hard coded url in your template. You can give the urls in your urls.py names. Then in your template, you can reference these names so that if your urls.py path ever changes, your templates refer to the name and not the hard coded path.

So:

<form action="/season_detail/{{ choice.year }}" method="get">

Becomes (season_detail is the name from urls.py):

<form action="{% url "season_detail" choice.year %}" method="get">

Leave a comment