Setting a form field's default value from a request variable
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开发者_如何学Go available in the request
variable without passing it explicitly to the form.
Thanks.
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
精彩评论