使用Django LocalFlavor Zip作为模型字段 [英] Working with Django LocalFlavor Zip as a Model Field

查看:106
本文介绍了使用Django LocalFlavor Zip作为模型字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下操作的最佳方法是:

  ### models.py 
>> >从django.db导入模型
>>>>从django.contrib.auth.models import User
#创建客户端类。
>>> class Client(models.Model):
... user = models.OntToOneField(User)
... zip = *** ??? ***()

### forms.py
>>>从django.forms import ModelForm
#创建表单类。
>>> classForm(ModelForm):
... class Meta:
... model = Client

我试图获得最终结果,使用美国邮政编码字段窗体小部件/验证器仅使用models.py文件修改...也可以不想执行以下操作:

  ### forms.py 
>>> from django.forms import ModelForm
>>>>从django.contrib.localflavor.us.forms import USZipCodeField
#创建表单类。
>>> classForm(ModelForm):
... class Meta:
... model = Client
... zip = USZipCodeField()
/ pre>

注意:这可能是最好的方法来完成它在forms.py文件如上所示...如果是这样,我猜我没有把它放在那里,而不是一个自定义的模型领域(例如,DRY?松耦合?)。在这种情况下,帮助更好地了解forms.py对models.py的好处的任何帮助将是非常感谢。



提前感谢!
-Tom

解决方案

邮政编码只是一串数字/字母,所以没有必要定义一个自定义字段用于将其存储在数据库中。目前在Django中没有模型级的验证(尽管有一个Google Summer of Code项目来添加它),所以自定义模型字段不会添加任何东西。验证来自于表单级别,这就是为什么有一个自定义表单字段。


What's the best way to implement the following:

### models.py
>>> from django.db import models
>>> from django.contrib.auth.models import User
# Create the client class.
>>> class Client(models.Model):
...     user = models.OntToOneField(User)
...     zip = ***???***()

### forms.py
>>> from django.forms import ModelForm
# Create the form class.
>>> class ArticleForm(ModelForm):
...     class Meta:
...         model = Client

I'm trying to get the end result to use the US Zip Codes Field form widget/validator using only modifications the models.py file... aka I don't want to do the following:

### forms.py
>>> from django.forms import ModelForm
>>> from django.contrib.localflavor.us.forms import USZipCodeField
# Create the form class.
>>> class ArticleForm(ModelForm):
...     class Meta:
...         model = Client
...     zip = USZipCodeField()

NOTE: It might be that the BEST way to accomplish it is in the forms.py file as shown above... If this is the case, I guess I'm missing the argument/benefit of having it there instead of as a custom model field (e.g., DRY?, loose coupling?) Any help on helping better understand the benefits of forms.py over models.py in this scenario would be greatly appreciated.

Thanks in advance! -Tom

解决方案

A zip code is just a string of numbers/letters, so there's no need to define a custom field for storing it in the database. There's no model-level validation in Django at the moment (although there's a Google Summer of Code project to add it), so a custom model field wouldn't add anything. The validation comes at the form level, which is why there's a custom form field.

这篇关于使用Django LocalFlavor Zip作为模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆