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

早过忘川 提交于 2019-11-27 15:07:35

问题


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?


回答1:


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 }



回答2:


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.



来源:https://stackoverflow.com/questions/13180116/how-do-i-set-initial-data-on-a-django-class-based-generic-createview-with-reques

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!