[英]Django: How do I access post data and match with a criteria
我需要一些关于以下最佳实践实施的指导。
我有一个场景,我正在构建一个应用程序,但如果它匹配某个“类别”或“区域设置”,并希望将其重定向到其他之间的页面只是去正常的路线。
这是我简单的views.py
if form.is_valid():
...
kwargs = {'project_id':project_id, 'categories':request.POST['categories'], 'locale':request.POST['locale']}
process_se(request, **kwargs)
return HttpResponseRedirect(obj.next_url)
这是我在models.py文件中的内容,但它似乎非常不一致。 有没有更好的方法来处理这个请求?
def process_se(self, request, **kwargs):
if "All" or "Sweden" in kwargs['locale']:
if "Technology" or "Internet" in kwargs['categories']:
next_url = request.build_absolute_uri(reverse('project_new_se', kwargs={'project_id': self.id}))
else:
next_url = request.build_absolute_uri(reverse('project_new_step2', kwargs={'project_id': self.id}))
self.next_url = next_url
更新:
我正在使用forms.ModelForm
, categories
和locales
是ManyToManyField
我在shell中模拟了一个for仍然似乎没有结果
这是cleaning_data输出
f.cleaned_data
{'locale': [<Locale: Sweden>, <Locale: All>], 'categories': [<Category: Technology>, <Category: Internet>]}
虽然对于表单中的字段运行此类似乎可以根据您的解决方案完美地呈现
我最初建议将此代码放在表单类中,但ApPeL修改了问题,指出locale
和categories
是模型上的多对多字段。 所以现在我建议在你的模型中放一个这样的方法:
def requires_swedish_setup(self):
"""
Return True if this project requires extra Swedish setup.
"""
return (self.locale.filter(name__in = ('All', 'Sweden')).exists())
and self.categories.filter(name__in = ('Technology', 'Internet')).exists())
然后像这样实现你的视图:
if form.is_valid():
project = form.save()
next = 'project_new_step2'
if project.requires_swedish_setup():
next = 'project_new_se'
next_url = reverse(next, kwargs={'project_id': project.id})
return HttpResponseRedirect(next_url)
一些说明:
我假设Locale
和Category
对象有name
字段(如果没有,请使用包含您正在测试的名称的任何字段)。
从request.POST
读取表单数据并不是一个好主意(小部件没有机会运行,并且尚未经过验证):最好使用form.cleaned_data
。
在这种情况下,您不需要调用request.build_absolute_uri
:可以将reverse
结果直接提供给HttpResponseRedirect
。
"All" or "Sweden" in kwargs['locale']
可能不是你的意思:它像"All" or ("Sweden" in kwargs['locale'])
解析,因此总是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.