How To Pass User Object To Forms In Django
How would I pass a user object or a request to my form for using it as an initial value for input textbox? For example, I have my form: class ContactForm(forms.Form): contact_name
Solution 1:
You have changed your form to take the request object. Therefore you can access self.request.user
inside your form's methods:
classContactForm(forms.Form):
...
def__init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Your name:"self.fields['contact_name'].initial = self.request.user.first_name
You also have to update your view to pass the request object. Remember to update the code for GET and POST requests.
if request.method == 'POST':
form = ContactForm(data=request.POST, request=request)
...
else:
# GET request
form = ContactForm(request=request)
Finally, by passing the request to the form, you have tightly coupled it to the view. It might be better to pass the user
to the form instead. This would make it easier to test the form separately from the view. If you change the form, remember to update the view as well.
Solution 2:
You need to pass the initial values in the view:
views:
defContactsView(request):
form_class = ContactForm(request=request,
initial={'contact_name': request.user.first_name})
...
Post a Comment for "How To Pass User Object To Forms In Django"