【问题标题】:Sending instance to ModelForm with custom fields使用自定义字段将实例发送到 ModelForm
【发布时间】:2010-07-04 21:27:45
【问题描述】:

我有一个用于管理用户的表单,一个 ModelForm 类型。但是对于两个字段,我需要一个 RegexField 来验证我的数据。因此,我需要覆盖这些字段。但是现在当我在编辑模式下打开表单时(发送我的用户实例时),我在两个字段中都没有加载任何数据。如何避免呢?我应该忘记正则表达式字段并为他们创建一个自定义清洁方法吗?

class UserForm(forms.ModelForm):        
    pid = forms.RegexField(regex=r'^\d{11}', max_length=11 ,widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)), error_messages=my_default_errors)
    code = forms.RegexField(regex=r'^\d{2}[-]\d{3}', max_length=6, widget=forms.TextInput(attrs=attrs_dict), label="Postal code", error_messages=my_default_errors)

    class Meta:
        model = UserProfile
        exclude = ( 'user', 'image', 'pid' , 'code')

型号:

class UserProfile(models.Model):
    def upload_path(self, field_attname):
        filename = hashlib.md5(field_attname).hexdigest()[:4] + "_" + field_attname
        return settings.MEDIA_ROOT + "/uploads/users/%s" % (filename,)
    first_name = models.CharField("Name", max_length=50, blank=True, null=True)
    last_name = models.CharField("Last name", max_length=50, blank=True, null=True)
    pid = models.CharField("PESEL", max_length=11, blank=True, null=True)
    street = models.CharField("Street", max_length=50, blank=True, null=True)
    number = models.CharField("Flat/house number", max_length=10, blank=True, null=True)
    code = models.CharField("Zip ", max_length=6, blank=True, null=True)
    city = models.CharField("City", max_length=50, blank=True, null=True)       
    user = models.ForeignKey(User, unique=True, related_name='profile')
    image = models.ImageField(upload_to=upload_path, verbose_name="Image", blank=True, null=True)

【问题讨论】:

    标签: django-forms validation


    【解决方案1】:

    您设置了新的字段类型,这是正确的,但随后您将它们排除在模型处理之外,但事实并非如此。从Meta.exclude 中删除它们。

    【讨论】:

    • 应该在这些字段之前声明 Meta,还是没有区别?
    • 没关系。无论如何,它们都被一大块地发送到元类。
    猜你喜欢
    • 2013-02-21
    • 2010-12-21
    • 1970-01-01
    • 2019-10-04
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    相关资源
    最近更新 更多