Django模板如何通过OneToOneField获取模型的值

huangapple go评论66阅读模式
英文:

Django Template how to get the value of a model through the OneToOneField

问题

在我的Django应用中,我有两个模型和来自django.contrib.auth.models的User模型。

在我的模板中,我正在遍历一个Room列表的对象,我需要获取UserPorfile中的avatar值。

我可以这样做吗?如果可以,如何做?有没有更好的解决办法?

以下是代码部分的翻译:

from django.contrib.auth.models import User

class Room(models.Model):
    host = models.ForeignKey(User, on_delete=models.CASCADE, null=True) 
    topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
    name = models.CharField(max_length=200)
    description = models.TextField(null=True, blank=True)
    participants = models.ManyToManyField(User, related_name='participants', blank=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-updated', '-created']

    def __str__(self):
        return self.name

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    about = models.TextField(max_length=250)
    avatar = models.ImageField(upload_to='avatars')

    def __str__(self):
        return self.user.username
{% for room in rooms %}
<div class="roomListRoom">
    <div class="roomListRoom__header">
        <a href="{% url 'user-profile' room.host.id %}" class="roomListRoom__author">
        <div class="avatar avatar--small">
           <img src="" /> <!-- This image should refer to the UserProfile linked to room.host-->
        </div>
        <span>@{{ room.host.username }}</span>
        </a>
        <div class="roomListRoom__actions">
        <span>{{ room.created|timesince }}</span>
        </div>
    </div>
</div>
{% endfor %}

请注意,上述模板中的<img src="">标签中应该包含指向与room.host相关联的UserProfile的avatar图像的URL。为了实现这一点,您可以在视图中将UserProfile与Room一起检索,然后在模板中引用avatar URL。这可以通过使用Django的select_related方法来实现,以最小化数据库查询的次数。这将是更好的解决方案,因为它将减少数据库查询次数。

英文:

In my Django App i have Two Models and the User model from django.contrib.auth.models

from django.contrib.auth.models import User

class Room(models.Model):
    host = models.ForeignKey(User, on_delete=models.CASCADE, null=True) 
    topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
    name = models.CharField(max_length=200)
    description = models.TextField(null = True, blank = True)
    participants = models.ManyToManyField(User, related_name=&#39;participants&#39;, blank = True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = [&#39;-updated&#39;, &#39;-created&#39;]

    def __str__(self):
        return self.name

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    about = models.TextField(max_length=250)
    avatar = models.ImageField(upload_to=&#39;avatars&#39;)

    def __str__(self):
        self.user.username

In my template i'm looping through objects of a Room list and i need to get the value avatar from UserPorfile

{% for room in rooms %}
&lt;div class=&quot;roomListRoom&quot;&gt;
    &lt;div class=&quot;roomListRoom__header&quot;&gt;
        &lt;a href=&quot;{% url &#39;user-profile&#39; room.host.id %}&quot; class=&quot;roomListRoom__author&quot;&gt;
        &lt;div class=&quot;avatar avatar--small&quot;&gt;
           &lt;img src=&quot;&quot; /&gt; &lt;!-- This image should refer to the UserProfile linked to room.host--&gt;
        &lt;/div&gt;
        &lt;span&gt;@{{room.host.username}}&lt;/span&gt;
        &lt;/a&gt;
        &lt;div class=&quot;roomListRoom__actions&quot;&gt;
        &lt;span&gt;{{room.created|timesince}}&lt;/span&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

Can i do this? If i can, how? Can i solve this problem in a better way?

答案1

得分: 1

{{ room.host.avatar.url }}
或者在你的情况下
Django模板如何通过OneToOneField获取模型的值
另外一点,为了减少数据库调用,你可能希望在选择房间列表时获取主机的详细信息,例如
rooms = Room.objects.filter(x=y).select_related('host')
否则,每次在房间循环中查找URL时,都需要再次进行数据库调用。

英文:

Assuming you are passing rooms in a a context variable to cycle through, you should be able to refer to the URL field directly (as per the docs)

{{ room.host.avatar.url }}

or in your case

&lt;img src=&quot;{{ room.host.avatar.url }}&quot; /&gt;

As a side note, to reduce database calls, you may want to grab the host details when you select your list of rooms, eg,

roooms = Room.objects.filter(x=y).select_related(&#39;host&#39;)

Otherwise every time you look for the URL in your rooms loop, you'll need to make another db call to grab the host details.

答案2

得分: 1

views.py中的用户资料中获取头像,然后通过上下文传递到HTML。

avatar = request.user.userprofile.avatar
context = {
    'avatar': avatar
}
英文:

You should retrive the avatar from user profile in views.py, then send to html via context.

code should be in views.py

avatar = request.user.userprofile.avatar 
context = {
&#39;avatar &#39;: avatar  
}

huangapple
  • 本文由 发表于 2023年7月17日 12:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定