我有这个小的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)
我想要“创造者”'要使用触发保存/更新操作的已记录用户自动填充的字段,以便我可以显示它但不允许直接更改。
当然,只要将这样的用户FK放在模型中,就会询问我输入哪个用户,我不想发生这种情况。
我已尝试过这两行:
creatore = models.ForeignKey(User, default=request.user.get_username())
creatore = models.ForeignKey(User, default=User.get_username())
但是没有一个工作,因为第一个错过了一个请求的实例,而第二个抱怨该方法是不(更正,感谢@bruno desthuilliers)被调用在一个实例上(" TypeError:未绑定方法get_username()必须使用User实例作为第一个参数调用(没有取而代之)")
这样做的简单方法是什么?
答案 0 :(得分:0)
模型没有“神奇”访问“当前请求”的事实是设计 - 因为不一定是“当前请求”,即从命令处理模型时 - 行脚本等。
处理问题的正确方法是从您的视图中明确传入“当前用户”(将请求作为第一个参数)。
作为旁注
您的AllegatoStrumento.__unicode__
实施已损坏(__unicode__
必须返回unicode
个对象,而不是str
个对象 - 提示: django模型中的所有文本字段都返回unicode)
您第二次尝试在模型中提供默认值时抱怨get_username()
无论如何,您的字段需要User
个实例,而不是用户名,因此对get_username()
的调用远离标记。