How to set source data based on Django-based generic create view with query data

I used a general view for Django for my model

from myproject.app.forms import PersonForm class PersonMixin(object): model = Person form_class = PersontForm class PersonCreateView(PersonMixin, CreateView): pass 

This works great for displaying the created Person view 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 the initial value of modelform in generic class-based views

However, my pre-populated value comes from the profile for request.user. How to access the request in PersonCreateView and submit it to the form?

+7
source share
2 answers

In any of the class methods, you can access the request using self.request. This way your user profile will be accessible using self.request.user.

Based on the link you provided, you can use self.request.user in the get_initial method to set the value.

t

 def get_initial(self): return { 'value1': self.request.user } 
+30
source

Firstly, you do not need to use mixin. Just specify form_class in PersonCreateView ; a model is also not needed, as you already specify it in form_class (assuming that it is a subclass of ModelForm ).

About where to get a request from classes based on a class, store it in an object so that you can do self.request.user inside get_initial or get_form_kwargs .

+3
source

All Articles