我有一个简单的表单和一个基本正在做的事情的视图:
from annoying.decorators import ajax_request
@require_POST
@login_required
@ajax_request
def my_view(request):
form = MyForm(request.POST)
if form.is_valid():
form.save(request.user)
return {"ok": True}
return {"ok": False, "errors": form.errors}
forms.py:
class MyForm(forms.Form):
name = forms.CharField(max_length=250)
def clean_name(self):
cleaned_data = self.cleaned_data
name = cleaned_data.get('name', '')
if MyModel.objects.filter(name__iexact=name).exists():
raise forms.ValidationError(_(u"This already exists."))
return cleaned_data
def save(self, user):
obj, created = MyModel.objects.get_or_create(name=self.cleaned_data["name"], user=user)
return obj
但我在form.save
方法中获取self.cleaned_data时遇到问题。
在MyForm.clean_name
我的self.cleaned_data很酷。
但在form.save
级别,self.cleaned_data = {'name':{...}}
self.cleaned_data ['name']也是如此。等等..还有self.cleaned_data ['name'] ['name'] ['name'] ['name'] ['name'] ... ['name'] ['name']
键入(self.cleaned_data),其键是dict
什么可以使我的代码表现得那样?
答案 0 :(得分:5)
您的问题是clean_<fieldname>
应该返回已清理的值,而不是整个cleaned_data
字典:
def clean_name(self):
cleaned_data = self.cleaned_data
name = cleaned_data.get('name', '')
if MyModel.objects.filter(name__iexact=name).exists():
raise forms.ValidationError(_(u"This already exists."))
return name