gpt4 book ai didi

django - 在一个 Django View 上获取 "This QueryDict instance is immutable",但在另一个 View 上却没有

转载 作者:行者123 更新时间:2023-12-02 02:27:50 27 4
gpt4 key购买 nike

我有两个 View ,一个在表单无效时尝试添加到 POST 数据时工作正常,另一个在尝试执行相同操作时给出“此 QueryDict 实例是不可变的”错误。我知道这些观点太相似而无法首先存在,并计划将它们结合起来……但我想首先了解导致其中一个失败的区别是什么。

这个 View 工作正常:

@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))

但是当 View 无效时,尝试用“干净”数据填充 request.POST['brag'] 时,此 View 给了我一个“此 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

最佳答案

想通了。这是因为我在模板中调用表单的方式。如果将 enctype 更改为 multipart,则不会再收到错误。这绝不是一个解决方案,您应该考虑在表单类而不是 View 中执行此操作。但我想弄清楚为什么它会以一种方式起作用,而不是另一种方式。

<form action="." method="post" class="genForm" enctype="multipart/form-data">

对比

<form action="." method="post" class="genForm">

这似乎可能是 Django 中的一个错误(为什么不在这两种情况下强制执行?)

由于这个答案似乎有些困惑,我这里有一个更简单的示例,显示了相同的结果:

查看:

def testit(request):
if request.method == "POST":
form = testForm(request.POST, request.FILES)
clean = 'Going to stuff post data with this string'
if form.is_valid():
print 'valid'
request.POST['testOne'] = clean
else:
print 'not valid'
request.POST['testOne'] = clean
else:
form = testForm()
return render_to_response('brag_board/test.html', {'form':form}, context_instance=RequestContext(request))

表格:

class testForm(forms.Form):
testOne = forms.CharField(required=True)
testTwo = forms.CharField(required=True)

出现错误的模板:

<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>

<form action="." method="post" class="genForm">
{{ form }}
{% csrf_token %}
<button type="submit" name="action" value="addnewsletter">test</button>
</form>

</body>
</html>

不报错的模板:

<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>

<form action="." method="post" class="genForm" enctype="multipart/form-data">
{{ form }}
{% csrf_token %}
<button type="submit" name="action" value="addnewsletter">test</button>
</form>

</body>
</html>

关于django - 在一个 Django View 上获取 "This QueryDict instance is immutable",但在另一个 View 上却没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18549190/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com