How to access data when form.is_valid() is false

2019-03-10 13:11发布

When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.

I'm trying to access forms within a form set, so form.data seems to just give me a mess.

7条回答
干净又极端
2楼-- · 2019-03-10 14:02

I ran into a similar problem using a formset. In my example, I wanted the user to select a 1st choice before a 2nd choice, but if the 1st choice hit another error, the 'select 1st choice before 2nd' error was also displayed.

To grab the 1st field's uncleaned data, I used this within the form field's clean method:

dirty_rc1 = self.data[self.prefix + '-reg_choice_1']

Then, I could test for the presence of data in that field:

if not dirty_rc1:
    raise ValidationError('Make a first choice before second')

Hope this helps!

查看更多
登录 后发表回答