【问题标题】:Accessing objects parent property in django profiles访问 django 配置文件中的对象父属性
【发布时间】:2012-07-31 17:36:25
【问题描述】:

我正在使用具有不同类型配置文件的 django 配置文件。

我的公司简介模型类似于:

from django.db import models
from django.contrib.auth.models import User
from accounts.models import UserProfile
from jobs.models import City
from proj import settings
from django.core.mail import send_mail

class Company(UserProfile):
    name=models.CharField(max_length=50)
    short_description=models.CharField(max_length=255)
    tags=models.CharField(max_length=50)
    profile_url=models.URLField()
    company_established=models.DateField(null=True,blank=True)
    contact_person=models.CharField(max_length=100)
    phone=models.CharField(max_length=50)
    address=models.CharField(max_length=200)
    city=models.ForeignKey(City,default=True)

    def send_activation_email(self):
        self.set_activation_key(self.username)
        email_subject = 'Your  '+settings.SITE_NAME+' account confirmation'
        email_body = """Hello, %s, and thanks for signing up for an                                                                                            
example.com account!\n\nTo activate your account, click this link within 48                                                                                       
hours:\n\nhttp://"""+settings.SITE_URL+"/accounts/activate/%s""" % (self.username,self.activation_key)
        send_mail(email_subject,
                  email_body,
                  'acccounts@site.com',
                  [self.email])

在这里,我从 UserProfile 继承 Company,并在发送激活电子邮件时,尝试使用父类 user 和 userprofile 的属性和方法。它的直接父级是用户配置文件,而用户与用户配置文件具有一对一的关系。因此,我尝试调用在 userpofile 中定义的 self.activation_key 并调用 self.username ,这是用户类/表的属性,并且在 self.username 上出现错误。

看来我以错误的方式调用 self.username ,那么我该如何访问 self.username ?任何细节都会有所帮助和赞赏。

【问题讨论】:

  • 如果我理解正确,您的层次结构是 User -> UserProfile -> Company?
  • @themanatuf 是的,你理解正确
  • 你能在调用self.activation_key之前尝试打印self.username吗? self.activation_key 方法是静态的吗?
  • @themanatuf 感谢您的时间和精力,我需要像 Daniel Roseman 所说的那样实际使用 self.user.username

标签: django django-models django-profiles


【解决方案1】:

Company 继承自 UserProfile,但正如您所说,UserProfile 不继承自 User - 它与它具有 OneToOne 关系。所以没有self.username 这样的东西——只是从selfUser.username 的关系。我猜测这种关系是通过一个名为user 的字段实现的,在这种情况下,您需要self.user.username

【讨论】:

    猜你喜欢
    • 2015-06-26
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多