如何使用请求数据在基于 Django 类的通用 createview 上设置初始数据 [英] How do I set initial data on a Django class based generic createview with request data

查看:26
本文介绍了如何使用请求数据在基于 Django 类的通用 createview 上设置初始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的模型使用了 Django 的通用 createview

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

这非常适合使用我的自定义表单显示 Person 的创建视图.但是,我在表单中有一个字段,我想用一个值预填充它.我找到了这个答案:在课堂上将初始值设置为 modelform基于通用视图

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

但是,我预先填充的值来自 request.user 的配置文件.如何访问 PersonCreateView 中的请求并将其传递给表单?

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?

推荐答案

在任何类方法中,您都可以使用 self.request 访问请求.因此,您的用户个人资料将可以通过 self.request.user 访问.

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.

基于您提供的链接,您将能够在 get_initial 方法中使用 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.

即.

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

这篇关于如何使用请求数据在基于 Django 类的通用 createview 上设置初始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆