我遇到了一个问题,我的表单没有在失败的表单提交中保留表单字段值。问题是,我希望用户可以看到它们无法选择任何其他状态(因为它是专门针对州内某个城市的网站),所以我禁用了它。如果我删除此窗口小部件属性,它会保留字段信息,否则,它会重置,我无法编辑该字段,因为我已将其禁用。请求补救措施或建议。代码如下。
forms.py
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Resource
from localflavor.us.forms import USStateSelect
from localflavor.us.forms import USZipCodeField
import pickle
zips = pickle.load(open('../zips.p', "rb"))
def validate_zip(zip_code):
"""Ensure zip provided by user is in King County."""
if zip_code not in zips:
raise ValidationError(
'{} is not a valid King County zip code.'.format(zip_code),
params={'zip_code': zip_code},
)
class ResourceForm(ModelForm):
"""Form for editing and creating resources."""
zip_code = forms.IntegerField(validators=[validate_zip])
class Meta:
model = Resource
fields = ['main_category', 'org_name',
'description', 'street', 'city', 'state', 'zip_code', 'website',
'phone_number', 'image', 'tags']
labels = {
'org_name': 'Name of Organization',
'main_category': 'Main Categories',
}
help_texts = {
'main_category': 'The core services your organization provides.',
}
widgets = {
'state': USStateSelect(attrs={'disabled': True}),
}
models.py(fields)
org_name = models.CharField(max_length=128)
description = models.TextField(max_length=512)
street = models.CharField(max_length=256, null=True, blank=True)
city = models.CharField(max_length=256, default='Seattle')
state = USStateField(default='WA')
zip_code = USZipCodeField(null=True, blank=True)
website = models.URLField(blank=True, null=True)
phone_number = PhoneNumberField()
tags = TaggableManager(blank=True)
image = models.ImageField(upload_to='photos', null=True, blank=True)
views.py(仅针对此视图)
class CreateResource(LoginRequiredMixin, CreateView):
"""Class-based view to create new resources."""
template_name = 'searchlist/resource_form.html'
form_class = ResourceForm
success_url = reverse_lazy('home')
答案 0 :(得分:1)
浏览器会忽略设置了disabled
属性的输入。改为在输入上设置readonly
;输入将不可编辑,但在提交表单时将包含其值。
widgets = {
'state': USStateSelect(attrs={'readonly': True}),
}