只是在黑暗中拍摄,但也许有人能够提出一些有趣的事情。
每当我在视图中有表单时,就会有很多 if-else 语句,并且很难遵循逻辑。是否有一些模式或python语言功能来简化这个?只要我记得,我就遇到过这个问题,并且今天找不到好的解决方案。
以下是一个示例:如果存在错误则呈现相同页面的视图,如果一切正常,则搜索(在模型上)并返回带有图形的页面:
def analysis(request):
context = {'main_navigation' : 'analysis'}
context['no_results'] = False
template = 'analysis/analysis.html'
# Search params?
if not request.GET:
form = AnalysisSearchForm()
context['form'] = form
else:
form = AnalysisSearchForm(request.GET)
context['form'] = form
if form.is_valid():
# Do the search
results = form.search()
if len(results) > 0:
context['results'] = json.dumps(results, default=encode)
context.update(form.cleaned_data)
# Add the compare form
context['compare_form'] = CompareForm();
# Add critical level if there is one.
part = form.cleaned_data.get('part', None)
if part:
level = Level.get(part, "Default")
if level is not None:
context['level'] = level.value
template = 'analysis/analysis_graphs.html'
else:
context['no_results'] = True
return render_to_response(template, context,
context_instance=RequestContext(request))
正如您所看到的,通过将所有查询逻辑移动到 form.search()方法已经简化了上述操作,该方法使用表单的cleaning_data(在本例中)联系远程API并获取结果。
答案 0 :(得分:1)
您是否看过基于类的视图(1.3中的新内容)。您将视图编写为类,并从多个基本视图和mixin继承必要的功能。这意味着您可以将您的视图分解为其组成部分并具有良好的代码分离:
https://docs.djangoproject.com/en/dev/topics/class-based-views/
此外,还有专门用于处理表格的mixin:
https://docs.djangoproject.com/en/dev/ref/class-based-views/#formmixin
他们需要一些阅读才能充分利用它们,但我真的很喜欢它的实现,看起来它是克服你提到的一些问题的好方法。
答案 1 :(得分:0)
这里我将如何做(有小变化和跳跃我没有打破功能逻辑):
# XXX: Use Dependency injection with the template file.
def analysis(request, template='analysis/analysis.html'):
context = {'main_navigation' : 'analysis'}
context['no_results'] = False
# XXX: Create only one form here without the need for if else.
form = AnalysisSearchForm(request.GET or {})
context['form'] = form
if form.is_valid():
# The rest of your code here ... .