相关模型字段未显示

时间:2016-02-01 19:13:51

标签: python html django

我无法理解代码中的错误。请有人告诉我为什么locations = Location.objects.filter(user=add_profile.user)中的字段不会显示在我的html页面中。

models.py

class Location(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    my_location = models.CharField(max_length=120, choices=LOCATION_CHOICES)
    update_date = models.DateField(auto_now=True, null=True)
    date = models.DateField()

def __str__(self):
    return self.my_location


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    user_base = models.CharField(max_length=120, choices=LOCATION_CHOICES)
    user_position = models.CharField(max_length=120)
    user_phone = models.CharField(max_length=50)
    first_name = models.CharField(max_length=120, null=True)
    last_name = models.CharField(max_length=120, null=True)
    slug = models.SlugField()

def save(self, *args, **kwargs):
    self.slug = slugify(self.user)
    super(UserProfile, self).save(*args, **kwargs)

def __unicode__(self):
    return self.user.username

views.py

@login_required
def details(request, user_slug):
    add_profile = UserProfile.objects.get(slug=user_slug)
    locations = Location.objects.filter(user=add_profile.user)
    print(locations)
    context = {'add_profile': add_profile, locations: "locations"}
    return render(request, 'details.html', context)

但是,print(locations)正在我的cmd中打印请求的数据。

html代码



{% for l in locations %}
    <ul>
        <li> {{l.my_location}} </li>
    </ul>
{% endfor %}
&#13;
&#13;
&#13;

我的问题是我没有任何错误,知道在哪里看。

谢谢。

1 个答案:

答案 0 :(得分:1)

而不是

context = {'add_profile': add_profile, locations: "locations"}

应该是

context = {'add_profile': add_profile, 'locations': locations}

您没有使用locations作为上下文的值,而是将其用作键和值仅仅是字符串&#34; locations&#34;。