我加载表单。我需要在文本字段city
中显示初始值。
模特:
class City(models.Model):
city = models.CharField(
max_length=40, blank=True,
)
class UserProfile(User):
family = models.CharField(
'Фамилия', max_length=30, blank=True, null=True,
)
city = models.ForeignKey(
City, verbose_name='Город', max_length=50, blank=True, null=True,
)
形式:
class PersonalDataForm(forms.ModelForm):
city = forms.CharField(
label='Город',
required=False,
)
class Meta:
model = UserProfile
fields = (
'family',
)
def save(self):
obj = super(PersonalDataForm, self).save(commit=False)
city_name = self.cleaned_data.get('city', None).strip()
if city_name:
if City.objects.filter(city=city_name).exists():
obj.city = City.objects.get(city=city_name)
else:
rec = City(city=city_name)
rec.save()
obj.city = rec
else:
obj.city = None
return obj.save()
观点:
def personal_data_page(request):
entry_user_profile = UserProfile.objects.get(user_ptr_id=request.user.id)
form = PersonalDataForm(instance=entry_user_profile)
if request.method == 'POST':
form = PersonalDataForm(request.POST, instance=entry_user_profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/userprofile/personal_data_page_changed/')
t = loader.get_template('personal_data_page.html')
c = RequestContext(request, {
'form': form,
}, [custom_proc])
return HttpResponse(t.render(c))
template.html:
{{ family.city }}
{{ form.city }}
问题是加载表单字段'city'时为空。但它必须包含表中的值(表格中的值)
答案 0 :(得分:1)
如果使用此模式,则应显示初始值:
if request.method=='POST':
data=request.POST
else:
data=None
form=MyForm(data, initial=...)
if (not data is None) and form.is_valid():
form.save()
return django.http.HttpResponseRedirect(...)
return HttpResponse(render(...))