两个相关模型,通过request.user访问数据

时间:2016-03-06 13:57:56

标签: django django-models django-views

我有点难过。所以我有两个模型,如models.py

所示
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    activation_key = models.CharField(max_length=40, blank=True)
    key_expires = models.DateTimeField(default=datetime.date.today())

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

    class Meta:
        verbose_name_plural='User profiles'


class ImageDoc(models.Model):
    user = models.ForeignKey(UserProfile)
    imgfile = models.ImageField(upload_to='images/')

这是一个简单的个人资料功能,我尝试做的只是在用户登录后显示与用户相关的图片。

这是我的views.py文件:

def sign_in(request):
    context = RequestContext(request)

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/', context)
            else:
                return HttpResponse("Verify your account!")
        else:
            return HttpResponse("Invalid login details supplied.")


def populateContext(request, context):
    context['authenticated'] = request.user.is_authenticated()
    if context['authenticated'] == True:
        context['username'] = request.user.username


def index(request):
    context = {}
    populateContext(request, context)

    context.update(image_gallery = ImageDoc.objects.only('imgfile'))
    return render(request, 'index.html', context)

在index.html页面中,我可以显示已登录的用户,这要归功于上面的populateContext。这包括:

{{ request.user.first_name }} {{ request.user.last_name }} {{ request.user.username }} {{ request.user.email }} {{ request.user.id }}

但是,我不知道如何显示" imgfile"来自相关模型。如果我这样做,它可以工作:

{% for x in image_gallery %}
    <img src="{{ x.imgfile }}"> 
{% endfor %}

但仅仅是因为我更新了上面的上下文以将其包含在内。理想情况下,我希望图像只显示在特定用户的页面上。完全像一个成员画廊。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以为UserProfile模型编写一个简单的方法,该方法将返回与当前images相关的所有user

class UserProfile(models.Model):
    # some stuff here

    def get_images(self):
        return ImageDoc.objects.filter(user=self)

现在您可以在模板中访问images

{% for image in user.userprofile.get_images %}
    <img src="{{ image.imgfile }}">
{% endfor %}