gpt4 book ai didi

python - 验证 Django 表单中的 ModelChoiceField

转载 作者:太空宇宙 更新时间:2023-11-03 19:38:01 25 4
gpt4 key购买 nike

我正在尝试验证包含 ModelChoiceField 的表单:

表单.py:

from django import forms

from modelchoicetest.models import SomeObject

class SomeObjectAddForm(forms.ModelForm):
class Meta:
model = SomeObject

模型.py:

from django.db import models

class SomeChoice(models.Model):
name = models.CharField(max_length=16)

def __unicode__(self):
return self.name

class SomeObject(models.Model):
choice = models.ForeignKey(SomeChoice)

views.py:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from forms import SomeObjectAddForm

def add(request):
if request.method == 'POST':
form = SomeObjectAddForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('modelchoicetest_add'))
else:
form = SomeObjectAddForm()

return render_to_response('modelchoicetest/index.html',
{'form': form},
context_instance=RequestContext(request))

正常情况下使用,一切正常。但我想保护表单免受无效输入的影响。很明显,当我在此字段中输入无效值时,我必须得到 forms.ValidationError ,不是吗?但是,如果我尝试提交“somechoice”字段中值为“invalid”的表单,我会得到

ValueError: invalid literal for int() with base 10: 'invalid'

而不是预期的形式。ValidationError。我应该怎么办?我尝试放置一个 def clean_somechoice(self) 来检查此字段,但这不起作用:ValueError 发生在它来到 clean_somechoice() 之前>

另外,我认为这不是一个好的解决方案,必须有更简单的东西,但我只是错过了。

这是完整的回溯:

Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
101. response = callback(request, *callback_args, **callback_kwargs)
File "/home/andrey/public_html/example/modelchoicetest/views.py" in add
11. if form.is_valid():
File "/usr/local/lib/python2.6/dist-packages/django/forms/forms.py" in is_valid
120. return self.is_bound and not bool(self.errors)
File "/usr/local/lib/python2.6/dist-packages/django/forms/forms.py" in _get_errors
111. self.full_clean()
File "/usr/local/lib/python2.6/dist-packages/django/forms/forms.py" in full_clean
276. value = field.clean(value)
File "/usr/local/lib/python2.6/dist-packages/django/forms/fields.py" in clean
154. value = self.to_python(value)
File "/usr/local/lib/python2.6/dist-packages/django/forms/models.py" in to_python
911. value = self.queryset.get(**{key: value})
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in get
330. clone = self.filter(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in filter
536. return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in _filter_or_exclude
554. clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py" in add_q
1109. can_reuse=used_aliases)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py" in add_filter
1048. connector)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/where.py" in add
66. value = obj.prepare(lookup_type, value)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/where.py" in prepare
267. return self.field.get_prep_lookup(lookup_type, value)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.py" in get_prep_lookup
314. return self.get_prep_value(value)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.py" in get_prep_value
496. return int(value)

Exception Type: ValueError at /
Exception Value: invalid literal for int() with base 10: 'invalid'

最佳答案

在我看来,异常是由 clean 引发的。实际的方法ModelChoiceField目的。因为它是外键,所以 Django 期待 int ,这将代表 pk对于 SomeChoice 。你到底是怎么通过的invalid进入表格?

回复评论

如果您确实觉得需要捕获这一点,您可以尝试覆盖默认值 ModelChoiceField通过创建一个名为 choice 的新字段并传入to_field_name kwarg进入ModelChoiceField __init__方法。这样 Django 就不会过滤 pk,也不会引发该异常。

我个人不会使用这个解决方案。无需容纳正在侵入您表单的用户。

关于python - 验证 Django 表单中的 ModelChoiceField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2400548/

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