3
3
3ds2012-02-02 12:42:28
Django
3ds, 2012-02-02 12:42:28

Django ModelForm set initial value?

I have this form:

# -*- coding: utf-8 -*-
from account.models import UserProfile, City, Country
from django.forms import ModelForm
from django import forms
from django.utils.safestring import mark_safe

class UserProfileForm(ModelForm):
  country = forms.ChoiceField()
  city = forms.ChoiceField()
  
  def __init__(self, *args, **kwargs):    
    super(UserProfileForm, self).__init__(*args, **kwargs)
    self.fields['country'].choices = self.get_country_choices(*args, **kwargs)
    if kwargs.has_key('country'):
      self.fields['country'].initial = self.initial['Country']

    #если так - то пустой select вылазит
    #self.fields['city'].queryset = City.objects.all()

    self.fields['city'].choices = self.get_city_choices(*args, **kwargs)
    if kwargs.has_key('city'):
      self.fields['city'].initial = self.initial['City']
              
  class Meta:
    model = UserProfile
    
  def get_country_choices(self, *args, **kwargs):
    choices = ()
    countries = Country.objects.all()
    for country in countries:
      choices += ((country.id, country.country),)
    return choices
    
  def get_city_choices(self, *args, **kwargs):
    try:
      country = self.initial['Country']
    except:
      country = None
                
    if country is None:
      return ()
    choices = ()
    cities = City.objects.filter(country=country)
    for city in cities:
      choices += ((city.id, mark_safe('%s, %s' % (city.city, city.state))),)
    return choices
  
  
  
  

* This source code was highlighted with Source Code Highlighter.


I call it in view like this (specially with initial parameters):

form = UserProfileForm(initial={'Country' : 20, 'City' : 4220060}, instance=profile)

* This source code was highlighted with Source Code Highlighter.


The question is why are the initial values ​​​​not affixed? Although the cities are chosen by country. But the selected element for the select is not set ... What can be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
3
3ds, 2012-02-02
@3ds

Hmm ... in modelform it is necessary to transfer objects (or is - instance after all)
Actually it was necessary that the cities were filtered by country. And just write:

class UserProfileForm(ModelForm):
  
  def __init__(self, *args, **kwargs):
   
    super(UserProfileForm, self).__init__(*args, **kwargs)
    try:
      country_id = self.instance.country.id    
      self.fields['city'].queryset = City.objects.filter(country=country_id)
    except:
      pass
              
  class Meta:
    model = UserProfile
    exclude = ('deleted', 'deletion_date', 'blocked_until', 'activation_key', 'blocked_times', 'test_fails',)
* This source code was highlighted with Source Code Highlighter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question