【问题标题】:Preserving disabled form field value in Django在 Django 中保留禁用的表单字段值
【发布时间】: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')

【问题讨论】:

  • 你能展示一下你的观点吗?
  • 抱歉,刚刚添加。

标签: python django forms


【解决方案1】:

浏览器会忽略设置了disabled 属性的输入。在输入上设置readonly;输入将不可编辑,但在提交表单时将包含其值。

    widgets = {
        'state': USStateSelect(attrs={'readonly': True}),
    }

【讨论】:

猜你喜欢
  • 2017-05-04
  • 2020-10-12
  • 2020-12-15
  • 2016-02-27
  • 2011-10-09
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 2020-12-06
相关资源
最近更新 更多