def __init__(self, request, data=None, files=None, *args, **kwargs): self.request = request if data is None and files is None: initial_data = kwargs.get('initial', {}) initial_data['csrf_token'] = new_csrf_token( self.request, identifier=identifier, ) kwargs['initial'] = initial_data super(InnerSafeForm, self).__init__(data, files, *args, **kwargs) self.fields['csrf_token'] = forms.CharField( widget = HiddenInputNoId, required = False, )
def clean(self): cleaned_data = super(InnerSafeForm, self).clean() token = cleaned_data.get('csrf_token', '') kwargs = dict(identifier=identifier) if expire_after is not not_set: kwargs['expire_after'] = expire_after if not token or not validate_csrf_token( token, self.request, **kwargs ): # Our form is "in flight", and we want the user to be able to # successfully resubmit it. This means we need to include a # freshly generated CSRF token in the hidden form field for # when the form is redisplayed with the validation error. if not (ajax_skips_check and self.request.is_ajax()): self.data._mutable = True self.data['csrf_token'] = new_csrf_token(self.request) self.data._mutable = False raise forms.ValidationError(invalid_message) return cleaned_data