python - 赋值前引用的局部变量'context_dict'

  显示原文与译文双语对照的内容
0 0

谁能解释一下这个错误意味着什么? 什么是任务context_dict应该是什么? 或者我做了其他错误? 我是 Django的新手。 非常感谢。

def add_page(request, category_name_slug):
 try:
 cat = Category.objects.get(slug=category_name_slug)
 except Category.DoesNotExist:
 cat = None
 if request.method == 'POST':
 form = PageForm(request.POST)
 if form.is_valid():
 if cat:
 page = form.save(commit=False)
 page.category = cat
 page.views = 0
 page.save()
 # probably better to use a redirect here.
 return category(request, category_name_slug)
 else:
 print form.errors
 else:
 form = PageForm()
 context_dict = {'form':form, 'category': cat}
 return render(request, 'rango/add_page.html', context_dict)

我收到了这个错误:

local variable 'context_dict' referenced before assignment

和异常正在指向与返回呈现( reqyest')/add_page 。html",context_dict的行

相同的回溯

时间:原作者:4个回答

0 0

记住在 python 缩进中很重要。 问题是变量 context_dict 在if语句外没有引用,因为它是如何缩进的。 因此,在if语句外声明变量 context_dict,如下所示:

 context_dict = {}
 if request.method == 'POST':
 <rest of code here>
原作者:
0 0

尝试这里代码只回复POST请求。

def add_page(request, category_name_slug):
 try:
 cat = Category.objects.get(slug=category_name_slug)
 except Category.DoesNotExist:
 cat = None
 if request.method == 'POST':
 form = PageForm(request.POST)
 if form.is_valid():
 if cat:
 page = form.save(commit=False)
 page.category = cat
 page.views = 0
 page.save()
 # probably better to use a redirect here.
 return category(request, category_name_slug)
 else:
 print form.errors
 else:
 form = PageForm()
 context_dict = {'form':form, 'category': cat}
 # indented - only reply to post requests
 return render(request, 'rango/add_page.html', context_dict)
 # if this is not a post request, raise an exception (handle your way later..)
 raise Exception('NOT A POST REQUEST')
原作者:
0 0

我再次考虑了代码,这种方式很有效。 我的context_dict现在位于if外语句and之外: form = PageForm() 在外部语句中,如果在内部语句中不像前面那样。 谢谢你们帮助我。

def add_page(request, category_name_slug):
 try:
 cat = Category.objects.get(slug=category_name_slug)
 except Category.DoesNotExist:
 cat = None
 if request.method == 'POST':
 form = PageForm(request.POST)
 if form.is_valid():
 if cat:
 page = form.save(commit=False)
 page.category = cat
 page.views = 0
 page.save()
 # probably better to use a redirect here.
 return category(request, category_name_slug)
 else:
 print form.errors
 else:
 form = PageForm()
 context_dict = {'category': cat, 'form': form}
 return render(request, 'rango/add_page.html', context_dict)
原作者:
...