0

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks - that looks like what I need to get on my way. I will take a look at the documentation and try your suggested answer..
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.