Django ModelForm установить initial value?

Имею такую форму:

# -*- 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 элемент для селекта не задается… Что сделать можно?
  • Вопрос задан
  • 11104 просмотра
Решения вопроса 1
3ds
@3ds Автор вопроса
Мде… в modelform надо объекты передавать (либо есть — instance ведь)
Собственно надо было чтоб города фильтровались по стране. И всего лишь написать:

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.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы