简体   繁体   English

无法使用OneToOne关系中的属性自动填充Django管理员字段

[英]Unable to autopopulate a Django admin field using an attribute from a OneToOne relationship

There are similar questions to this, but I believe mine is different. 对此有类似的问题,但我相信我的不同。 I am very new to Django and to Python, so please forgive my ignorance. 我是Django和Python的新手,所以请原谅我的无知。

I have a custom class UserProfile that inherits from the django.contrib.auth.models User class. 我有一个继承自django.contrib.auth.models User类的自定义类UserProfile。 This UserProfile is based on the exercise in Tango with Django, however, I am using the example to create a different project/app. 这个UserProfile基于Tango与Django的练习,但是,我使用这个例子来创建一个不同的项目/应用程序。

I have UserProfile linked to the standard User model with a OneToOneField relationship in my models.py, as shown below: 我将UserProfile链接到我的models.py中具有OneToOneField关系的标准用户模型,如下所示:

class UserProfile(models.Model):
    # Links UserProfile to a User model instance.
    user = models.OneToOneField(User)
    # The additional attribute I wish to include that isn't in User.
    slug = models.SlugField(unique=True)

In my admin.py file, I want an interface for UserProfile that I can work with, and I want the slugfield to autopopulate when I enter a new UserProfile. 在我的admin.py文件中,我想要一个可以使用的UserProfile接口,并且我希望在我输入新的UserProfile时slugfield自动填充。 I want it to autopopulate based on the username attribute of User. 我希望它根据User的username属性自动填充。 However, I can't seem to make it work. 但是,我似乎无法使其发挥作用。 Here is my admin.py code: 这是我的admin.py代码:

class UserProfileAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("user.username",)}

When I try to runserver from my command line, I get the following error: 当我尝试从命令行运行server时,出现以下错误:

ERRORS: <class 'climbcast.admin.UserProfileAdmin'>: (admin.E030) The
value of >'prepopula ted_fields["slug"][0]' refers to 'user.username',
which is not an attribute of >' climbcast.UserProfile'.

System check identified 1 issue (0 silenced).

It won't allow me to access the user.username attribute this way, even though I can access it that way in the python shell. 它不允许我以这种方式访问​​user.username属性,即使我可以在python shell中以这种方式访问​​它。 Any ideas on how to make this work? 关于如何使这项工作的任何想法?

Unfortunately prepopulated_fields doesn't accept DateTimeField , ForeignKey , nor ManyToManyField fields. 不幸的是, prepopulated_fields不接受DateTimeFieldForeignKeyManyToManyField字段。

Source: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields 资料来源: https//docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields

Possible solution, in your models.py (make slug attribute optional): 您的models.py中可能的解决方案(make slug属性可选):

from django.utils.encoding import force_text
from django.template.defaultfilters import slugify


class UserProfile(models.Model):
    [...]
    slug = models.SlugField(blank=True, db_index=True, unique=True)

    def get_unique_slug(self, value):
        """
        Generate a valid slug for a for given string.
        """
        qs = self.__class__.objects.all()
        used = qs.values_list('slug', flat=True)
        i = 1
        baseslug = slugify(value)
        while slug in used:
            slug = '%s-%s' % (baseslug, i)
            i += 1
        return slug

    def save(self, *args, **kwargs):
        if not self.slug and self.user:
          self.slug = self.get_unique_slug(force_text(self.user.username))
        super(UserProfile, self).save(*args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM