Python Django:如何访问post数据并与标准匹配
我需要一些关于以下最佳实践实施的指导 我有一个场景,我正在构建一个应用程序,但如果它与某个“类别”或“区域设置”匹配,并希望将其重定向到中间的页面,则只需按照正常的路线 这是我的简单视图.pyPython Django:如何访问post数据并与标准匹配,python,django,django-models,django-forms,django-views,Python,Django,Django Models,Django Forms,Django Views,我需要一些关于以下最佳实践实施的指导 我有一个场景,我正在构建一个应用程序,但如果它与某个“类别”或“区域设置”匹配,并希望将其重定向到中间的页面,则只需按照正常的路线 这是我的简单视图.py if form.is_valid(): ... kwargs = {'project_id':project_id, 'categories':request.POST['categories'], 'locale':request.POST['locale']} process_
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
更新:
我使用的是表单。ModelForm
,类别
和区域设置
是多个域
我在壳中模拟了一个for,但似乎仍然没有得到结果
这是数据输出
f.cleaned_data
{'locale': [<Locale: Sweden>, <Locale: All>], 'categories': [<Category: Technology>, <Category: Internet>]}
f.u数据
{'locale':[,],'categories':[,]}
尽管根据您的解决方案,对表单中的字段运行此命令看起来非常好,但我最初建议将此代码放入表单类中,但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
- 从
(小部件还没有机会运行,而且还没有经过验证):最好使用请求中读取表单数据不是一个好主意。POST
表单。清除数据
- 在这种情况下,您不需要调用
:可以将request.build\u absolute\u uri
的结果直接提供给reverse
HttpResponseRedirect
中可能不是您的意思:它的解析方式类似于“All”或“Sweden”在kwargs['locale']
,因此总是正确的“All”或(“Sweden”在kwargs['locale'])