我有两个视图,一个在表单无效时尝试添加到 POST 数据时工作正常,另一个在尝试做同样的事情时给我一个“这个 QueryDict 实例是不可变的”错误。我知道这些观点一开始就太相似了,无法将它们结合起来……但我想首先了解导致其中一个失败的区别是什么。
此视图工作正常:
@login_required
def url_parse(request):
cu = request.user
if request.method == 'POST':
form = UrlBragForm(request.POST, request.FILES)
if form.is_valid():
t = handle_image_upload(form.cleaned_data['image'],cu.pk,'url')
if t:
b = Brag()
b.user = cu
b.image = t
b.url = form.cleaned_data['url']
b.description = form.cleaned_data['brag']
b.active = True
b.timestamp = time.time()
b.save()
tags = parse_tags(form.cleaned_data['brag'])
if tags:
for tg in tags:
b.tags.add(tg)
else:
errors = form._errors.setdefault("image", ErrorList())
errors.append(u"There was an issue with your image. Please try again.")
else:
clean = cleanMessage(request.POST['brag'])
if clean != 'is_clean':
request.POST['brag'] = clean
else:
form = UrlBragForm()
return render_to_response('brag/url_brag.html', {'form':form,}, context_instance=RequestContext(request))
但是当视图无效时,当尝试用“干净”数据填充 request.POST['brag'] 时,这个视图给了我一个“这个 QueryDict 实例是不可变的”:
@login_required
def brag_add_image(request):
cu = request.user
if request.method == 'POST':
form = ImageAddBragForm(request.POST, request.FILES)
if form.is_valid():
t = handle_image_upload(form.cleaned_data['image'],cu.pk,'url')
if t:
b = Brag()
b.user = cu
b.image = t
b.description = form.cleaned_data['brag']
b.active = True
b.timestamp = time.time()
b.save()
b.url = 'http://%s%s' % (Site.objects.get_current().domain, reverse('image_display', args=(b.pk,)))
b.save()
tags = parse_tags(form.cleaned_data['brag'])
if tags:
for tg in tags:
b.tags.add(tg)
else:
errors = form._errors.setdefault("image", ErrorList())
errors.append(u"There was an issue with your image. Please try again.")
else:
clean = cleanMessage(request.POST['brag'])
if clean != 'is_clean':
request.POST['brag'] = clean
else:
form = ImageAddBragForm()
return render_to_response('brag/image_brag_add.html', {'form':form,}, context_instance=RequestContext(request))
这是要求的回溯:
Traceback:
File "site/src/django/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "site/src/django/django/contrib/auth/decorators.py" in _wrapped_view
20. return view_func(request, *args, **kwargs)
File "site/brag/views.py" in brag_add_image
241. request.POST['brag'] = clean
File "site/src/django/django/http/__init__.py" in __setitem__
439. self._assert_mutable()
File "site/src/django/django/http/__init__.py" in _assert_mutable
436. raise AttributeError("This QueryDict instance is immutable")
Exception Type: AttributeError at /brag/brag_add_image/
Exception Value: This QueryDict instance is immutable