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

Oli
  • 2,267
  • 5
  • 22
  • 21

2 Answers2

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

Community
  • 1
  • 1
Mikael
  • 3,148
  • 22
  • 20
  • 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.. – Oli Aug 16 '12 at 08:17
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.

Jonas Geiregat
  • 5,214
  • 4
  • 41
  • 60