I have a simple form and a view that are doing something as basic as:
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
But I have a problem at getting the self.cleaned_data in form.save method.
at the MyForm.clean_name my self.cleaned_data is cool.
But at form.save level, the self.cleaned_data = {‘name’: {…}}
Same for self.cleaned_data[‘name’]. wait for it.. but also self.cleaned_data[‘name’][‘name’][‘name’][‘name’][‘name’]…[‘name’][‘name’]
type(self.cleaned_data) and it’s keys is dict
what could make my code behave like that?
Your problem is that
clean_<fieldname>should be returning the cleaned value, not the entirecleaned_datadictionary: