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

后端 未结 2 1499
野趣味
野趣味 2020-12-15 11:12

I used Django\'s generic createview for my model

from myproject.app.forms import PersonForm
class PersonMixin(object):
    model = Person
    form_class = Pe         


        
相关标签:
2条回答
  • 2020-12-15 11:23

    First off, you don't need to use a mixin there. Just specify the form_class in PersonCreateView; model is not needed either, since you are already specifying it in the form_class (assuming is a subclass of ModelForm).

    About where to get the request from, class based views save it in the object, so you can do self.request.user inside get_initial or get_form_kwargs.

    0 讨论(0)
  • 2020-12-15 11:40

    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 }
    
    0 讨论(0)
提交回复
热议问题