How do I set initial data on a Django class based generic createview with request data

rsp picture rsp · Nov 1, 2012 · Viewed 12.8k times · Source

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?

Answer

jondykeman picture jondykeman · Nov 1, 2012

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 }