Django 如何根据选择字段验证请求的 URL?
我正在编写的应用程序中的一个模型中有一个选择字段。为了论证起见,它看起来像:
MANUFACTURERS = (
('sk','skoda')
('vw','volkswagen')
)
class car(models.Model):
manufacturer = models.CharField(max_length='2', choices=MANUFACTURERS)
现在,我想创建一个视图来列出制造商的所有汽车,我将视图连接起来以将制造商参数作为 URL 的一部分,但问题是验证这个确实是公认的制造商缩写,如“sk”或“vw”。
最初,我经历了一个棘手的过程:导入 MANUFACTURERS 常量,创建缩写列表,并检查给定值是否存在于该列表中。然后迭代 MANUFACTURERS 常量来获取全名。
for manufacturer in MANUFACTURERS:
manufacturers.append(manufacturer[0])
if url_given_mfn in manufacturers:
continue
else:
raise Http404
等等,这非常不优雅——有更好的解决方案吗?
I have a choice field in one of my models in an app I am writing. It looks, for arguments sake, like:
MANUFACTURERS = (
('sk','skoda')
('vw','volkswagen')
)
class car(models.Model):
manufacturer = models.CharField(max_length='2', choices=MANUFACTURERS)
Now, I want to create a view to list all the cars by a manufacturer, I wired up the view to take a manufacturer argument as part of the URL, but the issue is then validating that this is indeed an accepted manufacturer abbreviation as per 'sk', or 'vw'.
Initially I went through a hacky process of importing the MANUFACTURERS constant, creating a list of the abbreviations, and checking that the given value exists in that list. Then iterating the MANUFACTURERS constant to get the full name.
for manufacturer in MANUFACTURERS:
manufacturers.append(manufacturer[0])
if url_given_mfn in manufacturers:
continue
else:
raise Http404
etc. this is pretty inelegant - is there a better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我要做的是从可能的制造商中创建一个字典,例如:
这样您就可以查看键(缩写),如果您想检索值,只需执行以下操作:
您也可以在模型中执行该字典如果您愿意,只需导入即可。
What I would do is to make a dict out of the possible manufacturers, for example:
This way you are looking on the keys (the abrevation) and if you want to retrieve the value just do:
You could do the dict in the model too and just import it if you like.
我建议你使用 Django 表单。
因此,您必须验证表单。如果验证为 True,只需保存它,否则显示错误消息。
I will suggest you to use Django form for that.
so in view you have to just validate the form.If validate True just save it other wise show errot message.