[英]Automatically populate a model field with FK to User in Django
I have this small models.py file: 我有这个小的models.py文件:
models.py models.py
# -*- coding: utf-8 -*-
import datetime
from django.db import models
from django.contrib.auth.models import User
from apps.strumento.models import Strumento, Veicolo
class AllegatoStrumento(models.Model):
allegato = models.FileField(upload_to='uploads_strumento/', blank=True, null=True)
data_creazione = models.DateTimeField(default=datetime.datetime.now)
creatore = models.ForeignKey(User)
strumento = models.ForeignKey(Strumento)
class Meta:
verbose_name_plural = "Allegati strumenti"
verbose_name = "Allegato strumento"
def __unicode__(self):
return str(self.allegato)
I would like the 'creatore' field to be automatically populated with the logged user triggering the save/update action, so that I can display it but not allow it to be altered directly. 我希望“ creatore”字段自动由登录用户触发保存/更新操作来填充,以便我可以显示它,但不允许直接更改它。
OF course, just putting the User FK like this in the model, it asks me which user to put in, which I don't want to happen. 当然,只要将这样的User FK放入模型中,它就会问我要放哪个用户,我不想发生。
I've tried with both these lines: 我已经尝试了以下两行:
creatore = models.ForeignKey(User, default=request.user.get_username())
creatore = models.ForeignKey(User, default=User.get_username())
but none of them work, as the first misses an instance of request while the second complains that the method is NOT (corrected, thanks @bruno desthuilliers) being called on an instance (" TypeError: unbound method get_username() must be called with User instance as first argument (got nothing instead) ") 但它们都没有工作,作为第一错过的请求的实例,而第二抱怨的方法没有 (校正,由于@bruno desthuilliers)被称为上的一个实例(” 类型错误:未结合的方法get_username()必须与用户调用实例作为第一个参数(改为什么也不做) “)
What could an easy way for doing that be? 这样做的简单方法是什么?
The fact that models don't have a "magical" access to the "current request" is by design - because there's not necessarily such a thing as a "current request", ie when working on your models from a command-line script etc. 模型没有对“当前请求”的“魔术”访问的事实是设计使然的-因为不一定存在诸如“当前请求”之类的东西,即从命令行脚本处理模型等时。
The correct way to handle the problem is to explicitely pass in the "current user" from your views (which get the request as first argument). 解决问题的正确方法是从视图中显式传递“当前用户”(将请求作为第一个参数)。
As a side note 作为旁注
your implementation of AllegatoStrumento.__unicode__
is broken ( __unicode__
must return a unicode
object, not a str
object - hint: all text fields in django models return unicode) 您的AllegatoStrumento.__unicode__
已损坏( __unicode__
必须返回unicode
对象,而不是str
对象-提示:Django模型中的所有文本字段都将返回unicode)
your second attempt at providing a default in the model itself complains that get_username()
is not called on an instance 您在模型本身中提供默认值的第二次尝试抱怨没有在实例上调用get_username()
anyway, your field expects a User
instance, not a username so the call to get_username()
is way off mark. 无论如何,您的字段需要一个User
实例,而不是一个用户名,因此对get_username()
的调用是get_username()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.