Oli
Oli

Reputation: 2587

Changing django form values

I have a form that gets values from a database created by a model. Say my the table has 2 columns, city and code, and I display just the city in my form using a ModelChoiceField.

When the use submits the form and I am going through the validation process, I would like to change the value of the city the user has selected with it's code.

models.py

class Location(models.Model):
    city                = models.CharField(max_length=200)
    code                = models.CharField(max_length=10)

    def __unicode__(self):
        return self.city

forms.py

city = forms.ModelChoiceField(queryset=Location.objects.all(),label='City')

views.py

def profile(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():

            ???????

How could I do this?

Thanks - Oli

Upvotes: 0

Views: 278

Answers (2)

Jonas Geiregat
Jonas Geiregat

Reputation: 5442

I would overwrite the save method of the form. And change the field there. That way you still would have a clean view where all logic related to the form stays contained within the form.

Upvotes: 0

Mikael
Mikael

Reputation: 3234

You can do this:

def profile(request):
if request.method == 'POST':
    form = ProfileForm(request.POST)
    if form.is_valid():
        profile = form.save(commit=False)

        #Retrieve the city's code and add it to the profile
        location = Location.objects.get(pk=form.cleaned_data['city'])

        profile.city = location.code
        profile.save()

However you should be able to have the form setting the code directly in the ModelChoiceField. Check here and the django docs

Upvotes: 3

Related Questions