Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 812
rsp Avatar asked Nov 01 '12 15:11

rsp


1 Answers

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 }
like image 177
jondykeman Avatar answered Oct 20 '22 13:10

jondykeman