【发布时间】:2017-09-06 19:09:35
【问题描述】:
我遇到了一个问题,即我的表单未在表单提交失败时保留表单字段值。问题是我希望它对用户可见,他们无法选择任何其他州(因为它是专门针对州内城市的网站),所以我将其禁用。如果我删除此小部件属性,它会保留字段信息,否则,它会重置并且我无法编辑该字段,因为我已禁用它。请求补救或建议。代码如下。
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(字段)
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')
【问题讨论】:
-
你能展示一下你的观点吗?
-
抱歉,刚刚添加。