Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django admin中为模型使用构造函数_Python_Django - Fatal编程技术网

Python 如何在django admin中为模型使用构造函数

Python 如何在django admin中为模型使用构造函数,python,django,Python,Django,我正在为我的网站使用django管理员。 我有学生和管理员类是自动生成的形式 现在,我想根据登录的用户位置初始化学生模型本身中location的值 我不想在形式上做,但在模型上做类似的事情 class Student: def __init__(self): self.location = get_logged_user_location() 仅在Mdel中可以这样做吗 我正在这样努力 def __init__(self, *args, **kwargs):

我正在为我的网站使用django管理员。 我有学生和管理员类是自动生成的形式

现在,我想根据登录的用户位置初始化学生模型本身中location的值

我不想在形式上做,但在模型上做类似的事情

class Student:

   def __init__(self):
       self.location = get_logged_user_location()
仅在Mdel中可以这样做吗

我正在这样努力

def __init__(self, *args, **kwargs):
        super(Student, self).__init__(*args, **kwargs)
        self.name="test"

但它不起作用。我得到的是表单中的空文本字段

应该是:

def __init__(self, *args, **kwargs):
    self.name="test"
    super(Student, self).__init__(*args, **kwargs)

为什么不在您的姓名字段中输入默认值呢
name=models.CharField(默认值=get\u logged\u user\u location())
models可以在请求/响应阶段之外使用(例如从django shell),这不一定允许您访问请求或用户。设置数据的位置在表单中,或者可能在管理模型中。实际上,如果我这样做,我需要运行数据库迁移,我不想这样做。有没有办法在施工中做到这一点?你把它弄复杂了。可以使用modelforms初始化该值