I used Django's generic createview for my model
from myproject.app.forms import PersonForm
class PersonMixin(object):
model = Person
form_class = PersontForm
class PersonCreateView(PersonMixin, CreateView):
pass
This works perfectly for displaying a create view of Person with my custom form. However, I have a field in the form that I want to pre-populate with a value. I found this answer: Set initial value to modelform in class based generic views
However, my pre-populated value comes from the profile for request.user. How do I access the request in PersonCreateView and pass that to the form?
In any of the class methods you can access the request using self.request. So your user profile will be accessible with self.request.user.
Building on the link you provided you will be able to use self.request.user in your get_initial method to set the value.
ie.
def get_initial(self):
return { 'value1': self.request.user }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With