killajoule
killajoule

Reputation: 3832

How do you access the request object inside django forms.py?

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!

Upvotes: 0

Views: 1467

Answers (1)

mike_k
mike_k

Reputation: 1841

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)

Upvotes: 1

Related Questions