[Answer]-Django 1.5: How to show a preselected value passed from a view into a template select

1👍

You should use the forms framework. I’ll assume the pizza is stored in the UserProfile model.

First, create a forms.py file in your app that defines the form:

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['favorite_pizza', ]

Then, you could use an UpdateView or some custom view to use the form. Let’s assume we have an update view:

class UserProfileUpdateView(UpdateView):
    template_name = 'your_template'
    model = UserProfile
    form_class = UserProfileForm

Now, on to the template ‘your_template’:

<form method='post' action='.'>
    {% csrf_token %}
    {{ form.as_p }}
    <input type='submit' value='Confirm pizza change'/>
</form>

This way, django will render the select based on the choices you should specify in the definition of the favorite_pizza field. Also, this will handle setting the value to what the user has previously chosen.

Edit: I recommend doing the same in the registration page. In general, it will be a lot faster and safer to use the forms framework whenever you can to handle user input

👤Alvaro

Leave a comment