使用DetailView在Django中查看UserProfiles

时间:2018-03-28 12:41:47

标签: django django-views

我需要简单博客网站的帮助。用户可以在哪里写帖子。每个邮政作家都必须登录撰写帖子。但读者无需登录。

我正在使用django DetailView来允许读者查看Post作者的个人资料。

配置文件视图将包含作者的详细信息以及作者编写的其他帖子。

我使用以下逻辑来制作视图 https://chriskief.com/2012/12/29/django-generic-detailview-without-a-pk-or-slug/

以下是详细信息:

所有这些都在我网站的帐户应用中。下面的代码被破坏并给出错误

Image of the Error Message

账户/ views.py:

    class ProfileView(DetailView):
            model = User
            template_name = 'accounts/profile.html'

            def get_user_profile(self, username):   
                return get_object_or_404(User, pk=username)
     #I know pk=username is not correct. I am not sure what to put pk=?

  # I was able to get the writers other posts using the code below. I did not have to show this code for this question. But just to show you that the pk above has to be username. Or Else the code below won't work(I guess)        
            def get_context_data(self, **kwargs):
                context = super(ProfileView, self).get_context_data(**kwargs)
                context['post_list'] = Post.objects.filter(user__username__iexact=self.kwargs.get('username'))
                return context  

我的模型如下

账户/ models.py:

from django.contrib.auth.models import User
from django.db import models

    class UserProfile(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        city = models.CharField(max_length=100)
        country = models.CharField(max_length=100)
        bio = models.TextField(default='', blank=True)
        profile_image = models.ImageField(default='', blank=True, null='')


        def __str__(self):
            return "Profile of {}".format(self.user.username)

以下是我的模板

    {% extends 'base.html' %}

    {% block body %}
    <div class="content">
        <h1>{{user.first_name}} {{user.last_name}}</h1>
        <p>            
            <br/>From: City, Country
            <br/>Bio
            <br/>Profile Image
        </p>
    </div>


    {% endblock %}

账户/ urls.py

from django.conf.urls import url
from . import views
from django.contrib.auth.views import LoginView, LogoutView

app_name = 'accounts'

urlpatterns = [
    url(r'^login/$', LoginView.as_view(template_name='accounts/login.html'), name='login'),
    url(r'^logout/$', LogoutView.as_view(), name='logout'),
    url(r'^signup/$', views.SignUp.as_view(), name='signup'),
    url(r'^profile/(?P<username>[-\w]+)/$', views.ProfileView.as_view(), name='profile'),

]

错误消息文本

/ accounts / profile / 3 /的AttributeError 通用详细信息视图必须使用对象pk或slug调用ProfileView。 请求方法:GET 请求网址:http://127.0.0.1:8000/accounts/profile/3/ Django版本:1.11 异常类型:AttributeError 例外价值:
通用详细信息视图必须使用对象pk或slug调用ProfileView。 异常位置:get_object,第49行中的C:\ Users \ Samir \ Miniconda3 \ envs \ MyDjangoEnv \ lib \ site-packages \ django-1.11-py3.6.egg \ django \ views \ generic \ detail.py Python可执行文件:C:\ Users \ Samir \ Miniconda3 \ envs \ MyDjangoEnv \ python.exe Python版本:3.6.4 Python路径:.........

1 个答案:

答案 0 :(得分:2)

如果您使用“用户名”字段来获取用户,则可能需要 更改过滤器以使用“用户名”字段,因为它是唯一的:

尝试更改功能:

def get_user_profile(self, username):   
    return get_object_or_404(User, pk=username)

def get_object(self):
    return get_object_or_404(User, username=self.kwargs.get('username'))

OR

如果您希望该对象是UserProfile,请稍微将其更改为

def get_object(self):
        return get_object_or_404(UserProfile, user__username=self.kwargs['username'])