【发布时间】:2014-01-29 09:33:42
【问题描述】:
我有一个 unique_togeter = True 的模型,我正在使用 ModelForm 来验证它。
models.py
class Restrict(BaseModel):
user = models.ForeignKey(User)
title = models.ForeignKey('title')
active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True, default=datetime.now())
updated = models.DateTimeField(auto_now=True, default=datetime.now())
class Meta:
ordering = ["id"]
db_table = "editor_restrict"
app_label = "geral"
unique_together = ('user', 'title')
resources.py
class TitleResource(ModelResource):
class Meta:
queryset = Titulo.objects.all()
always_return_data = True
fields = ['name']
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
fields = ['username', 'email', 'first_name']
authentication = Authentication()
authorization = Authorization()
always_return_data = True
filtering = {
'username': ALL,
}
class RestrictResource(ModelResource):
user = fields.ForeignKey(UserResource, attribute='user', full=True)
title = fields.ForeignKey(TitleResource, attribute='title')
class Meta:
authentication = Authentication()
authorization = Authorization()
queryset = Restrict.objects.all()
resource_name = 'restrict'
always_return_data = True
fields = ['user', 'title', 'active']
serializer = Serializer()
validation = FormValidation(form_class=RestrictForm)
filtering = {
'user': ALL_WITH_RELATIONS,
}
当我做这样的 POST 时效果很好:
curl -H 'Content-Type: application/json' -X POST --data '{"active": true, "title": "/api/v1/titulo/16/", "user":"/api/v1/user/52831/"}' 'http://localhost:8000/api/v1/restrict/'
正如预期的那样,响应是状态代码:400 BAD REQUEST。
但是像这样的完整用户:
curl -H 'Content-Type: application/json' -X POST --data '{"active": true, "title": "/api/v1/titulo/16/", "user": {"username": "johnny@mail.com", "email": "johnny@mail.com", "first_name": "Johnny"}}' 'http://localhost:8000/api/v1/restrict/'
我得到 TypeError Exception int() 参数必须是字符串或数字,而不是来自 django 的“dict”。
UserResource 在所有 CRUD 中也都能正常工作。
如果我从 Model 中删除 unique_together,这个 POST 也可以正常工作。
我尝试调试,但无法弄清楚发生了什么。
问题是:我如何验证这个案例并返回正确的响应?
谢谢。
【问题讨论】:
标签: python django validation unique tastypie