[Answer]-Django Form 'int' object has no attribute 'required' for field that is added in function

1👍

self.fields['forum_id_number'] is an instance of a forms.Field subclass. It describes the attribute self.forum_id_number. The line self.fields['forum_id_number'] = response["User"]["Id"] overwrites this field description and sets it to an instance of an (Big?)Integer object. This instance of course has no attribute required.

The ‘correct’ way to set a value for forum_id_number is to use self.forum_id_number = response["User"]["Id"] or self.cleaned_data['forum_id_number'] = response["User"]["Id"].

Correct is in quotation marks because in this case it really isn’t the correct way. There is no way of knowing if the field forum_id_number is cleaned in any clean_FIELD method, so you don’t know if you should set self.forum_id_number or self.cleaned_data['forum_id_number']. Now in the case of forum_id_number, there is no security issue, but anyone with Firebug or something similar can change the value of user_assigned. It is generally better to exclude hidden fields from the form, and set the values on the instance itself in the save method of the form. Of course you can’t raise a ValidationError in the save method (well, you can, but it’d produce a 500 Internal Server Error), so you’ll have to get the user id in your clean_forum_username method:

class AccountForm(forms.ModelForm):
    ....
    def clean_forum_username(self):
        data = self.cleaned_data['forum_username']
        SLUG = "users/" + data + ".json"
        status_code, response = do_request(SLUG)
        if status_code != 200:
            raise forms.ValidationError("Your username was not"
                                        " found! Please check the"
                                        " the spelling. Also, your"
                                        " forum username is your"
                                        " forum sign in name.")
        elif status_code == 200:
            self.response = response
        return data

    def save(self, *args, **kwargs):
        # self.response should be valid, otherwise a `ValidationError` would've been raised
        self.instance.forum_id_number = self.response['User']['Id']
        return super(AccountForm, self).save(*args, **kwargs)
👤knbk

Leave a comment