如何在基于Django类的通用createview中设置请求数据的初始数据 [英] How do I set initial data on a Django class based generic createview with request data
问题描述
我使用Django的通用createview作为我的模型
from myproject.app.forms import PersonForm
/ pre>
class PersonMixin(对象):
model = Person
form_class = PersontForm
class PersonCreateView(PersonMixin,CreateView):
pass
这非常适合用我的自定义窗体显示Person的创建视图。但是,我有一个我想要预先填充一个值的形式的字段。我发现这个答案:将初始值设置为类中的modelform基本的通用视图
但是,我的预填充值来自request.user的配置文件。如何在PersonCreateView中访问请求并将其传递给表单?
解决方案在任何类方法中,您可以访问请求使用self.request。所以您的用户个人资料将通过self.request.user访问。
在您提供的链接上,您将可以在get_initial方法中使用self.request.user设置值。
ie。
def get_initial(self ):
return {'value1':self.request.user}
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?
解决方案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 }
这篇关于如何在基于Django类的通用createview中设置请求数据的初始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!