I'm running into an issue where my form is not preserving the form field value on a failed form submission. The catch is that I want it to be visible to the user that they can't select any other state (since it's a website specifically for a city within the state), so I have it disabled. If I remove this widget attribute, it preserves the field info, otherwise, it resets and I can't edit the field since I have it disabled. Request a remedy or a recommendation. Code follows.
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 (for this view alone)
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')