0

我有一个简单的表单和一个视图,它们正在做一些基本的事情:

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}

表格.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

但是我在获取 self.cleaned_dataform.save方法时遇到了问题。在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']

type(self.cleaned_data) 它的键是dict

是什么让我的代码表现得像这样?

4

1 回答 1

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
于 2012-10-29T17:32:55.890 回答