0

In Django, is it possible to set the default value of a form field to be tied to a request variable. e.g. request.META['REMOTE_ADDR'].

This is just an example, it'd like to be use any of the headers available in the request variable without passing it explicitly to the form.

Thanks.

1 Answer 1

1

No, it is not possible, since the request object is not globally available, and thus it is not available in the form unless explicitly passed in. The initial argument exists for exactly the problem you are trying to solve. You should probably use

form = YourForm(..., initial={'your_field': request.META['REMOTE_ADDR'])

in your view.

Edit:

If you like to pass in the request explicitly, you can use something like this, and then just pass request=request when you instantiates the form:

class YourForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(YourForm, self).__init__(*args, **kwargs)

    # ... use self.request in clean etc
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.