0

More specifically, I need to access the request object inside the init method of a form object. Here is my code:

class TagNamesField(forms.CharField):
    def __init__(self, user=None, *args, **kwargs):

        super (TagNamesField,self).__init__(*args,**kwargs)

        self.required = True
        self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
        self.max_length = 255
        self.label  = _('tags')
        #self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
        self.help_text = _('Tags are short keywords, with no spaces within. At least %(min)s and up to %(max)s tags can be used.') % {
            'min': settings.FORM_MIN_NUMBER_OF_TAGS, 'max': settings.FORM_MAX_NUMBER_OF_TAGS
        }
        self.initial = self.request.session['previous_url']
        self.user = user

Basically, I want to initialize this form: self.initial = self.request.session['previous_url']

Any ideas? Thanks!

1 Answer 1

1

Forms and widgets are decoupled from request informaton by design. Simple way to do what you want is to instantiate a form in a view this way:

form = SomeForm(initial={'tags': self.request.session['whatever']})

However, it might be more apropriate to create a custom form accepting request as an extra argument (giving form class acces to it):

form = SomeForm(request=request)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.