Django:获取模型字段中的当前用户名作为默认值

时间:2018-04-23 19:10:55

标签: django

 # models.py

from django.db import models
from django.contrib.auth.models import User

class SiteInfo(models.Model):
    site_owner = models.OneToOneField(User, on_delete=models.CASCADE, )
    site_url = models.CharField(max_length=40, unique=True, blank=False, default= site_owner, )

如何制作" site_url"默认值= User.username或site_owner实例?

2 个答案:

答案 0 :(得分:0)

据我所知,我不知道如何按照你想要的方式设置默认值,但是你可以覆盖save方法,它会做同样的事情

from django.db import models
from django.contrib.auth.models import User

class SiteInfo(models.Model):
    site_owner = models.OneToOneField(User, on_delete=models.CASCADE, )
    site_url = models.CharField(max_length=40, unique=True, blank=False)

    def save(self, *args, **kwargs):
        if self.pk is None:
            self.url = self.user.username
    super(SiteInfo,self).save(*args,**kwargs)

答案 1 :(得分:0)

您可以使用pre_save信号处理程序。

from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=SiteInfo)
def default_site_url(sender, instance, **kwargs):
     if not instance.site_url:
         instance.site_url = instance.site_owner.username

您需要在blank=True模型属性上设置site_url,否则表单验证绝不允许首先添加空白site_url