Имею такую форму:
# -*- 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.
вызываю ее во view так (специально с начальными параметрами):
form = UserProfileForm(initial={'Country' : 20, 'City' : 4220060}, instance=profile)
* This source code was highlighted with Source Code Highlighter.
Вопрос — почему не проставляются значения initial? Хотя города выбираются именно по стране. Но вот selected элемент для селекта не задается… Что сделать можно?