开发者

Django: accessing one-to-one field in templates

开发者 https://www.devze.com 2023-01-29 01:51 出处:网络
I have model UserProfile containing a OneToOneField on a class called Info开发者_如何学JAVA: class UserProfile(models.Model):

I have model UserProfile containing a OneToOneField on a class called Info开发者_如何学JAVA:

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    info = models.OneToOneField(Info, null = True, blank= True)

in my template I have access to the profile with

{{user.get_profile}}

but how to access Info? I have tried

{{user.get_profile.info.photo.url}}

without success.


You can't do that.

user.get_profile()

is a method and it gets executed when accessed as

{{user.get_profile}}

and not when you try to access more attributes of profile like {{user.get_profile.attr1}}

The way around is to send the profile object from the view. And if you want to have it in many view, you should make it a TemplateContextProcessor.

There is also another way of extending the User model with an attribute profile that is a @property that does the same as get_profile which you can do as I have described earlier.

0

精彩评论

暂无评论...
验证码 换一张
取 消