python - 通用详细 View UserProfileDetailView 必须使用对象 pk 或 URLconf 中的 slug 调用

标签 python django django-models django-views django-templates

好吧,我遇到了错误,这个问题已经过去两天了,但仍然停留在这个错误上,任何人都可以提供帮助并能够解决这个问题。我是 Django 的新手,需要帮助。我将感激不尽。如果除了告诉我之外还有什么需要答案,我会用那个细节更新我的问题.. 模型.py

class UserProfile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    follower = models.ManyToManyField(User, related_name ='is_following',blank=True)
    avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True)
    create_date = models.DateField(auto_now_add=True,null=True)
   


    def __str__(self):
        return f'{self.user.username}'

View .py

class UserProfileDetailView(DetailView):

    model = UserProfile
    template_name = "profiles/userprofile_detail.html"

    def get_context_data(self,*args, **kwargs):
            context = super().get_context_data(*args,**kwargs) 
            is_following = False
            if self.object.user in self.request.user.userprofile.follower.all():
                is_following = True
            context["is_following"] = is_following
            return context

网址.py

urlpatterns = [
    # path('user',UserProfileCreateView.as_view(template_name = 'profiles/userprofile.html'),name='home')
    # path('user/',userprofile,name = 'home'),
     path('user-profile/',UserProfileFollowToggle.as_view(),name = 'toggle'),
    path('<str:username>/',UserProfileDetailView.as_view(),name = 'detail'),
]

userprofile_detail.html

{% extends 'base.html' %}
{% block content %}
<p style="text-align: center;"><img src="{{ object.user.userprofile.avatar.url }}" width = "50%"></p>
{{ request.user.userprofile.follower.all }}<br>
{{object.user.userprofile }}
{% if object.user in request.user.userprofile.follower.all  %}
Following
{% endif %}
<p>{% include 'profiles/snippets/follow_toggle.html' with username=user.username is_following=is_following %}</p>
<h2>{{ object.username }}</h2>
/{{is_following}} 
{% endblock content %}

片段/follow_toggle.html

<form class='form' method='POST' action="{% url 'profiles:toggle'%}">
{% csrf_token %}
<input type='hidden' name='username' value="{% if username %}{{ username }}{% else %}hello{% endif %}">
<button class='btn {% if is_following %}btn-warning{% else %}btn-primary{% endif %}'>{% if is_following %}Unfollow {% else %}Follow{% endif %}</button>
</form>

错误回溯:

  Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/profiles/testuser/

Django Version: 3.0.3
Python Version: 3.8.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bootstrap3',
 'accounts',
 'posts',
 'profiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\detail.py", line 106, in get
    self.object = self.get_object()
  File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\detail.py", line 45, in get_object
    raise AttributeError(

Exception Type: AttributeError at /profiles/testuser/
Exception Value: Generic detail view UserProfileDetailView must be called with either an object pk or a slug in the URLconf.

最佳答案

问题

    在 urls.py 中使用
  1. str 类型代替 slug 类型
  2. UserProfileDetailView 未指定您的自定义 slug_url_kwargslug_field
  3. UserProfileDetailView 指定了 UserProfile 模型,但是 UserProfile 模型没有属性或方法 username,这是在`用户表。

解决方案

阅读 Django 的 DetailView 代码,您会发现以下内容是让您的代码正常工作所必需的。

更新类属性

View .py

class UserProfileDetailView(DetailView):
    slug_url_kwarg = "username"
    slug_field = "username"

更新 UserProfile 模型或更新 UserProfileDetailView.get_slug_field

UserProfile是为UserProfileDetailView和get_slug_field方法定义的查找表,其中读取slug_field属性在UserProfileDetailView上不支持点语法方法遍历(即: 用户.用户名`)。 因此:

  1. UserProfile 模型必须引用username 或;
  2. get_slug_field 必须显式定义 slug 字段或;
  3. get_slug_field 必须添加点语法方法遍历的功能

模型.py

class UserProfile(models.model):
    ...
    
    @property
    def username(self):
        self.user.username 

class UserProfileDetailView(DetailView):
    ...

    def get_slug_field(self):
        self.user.username

在 urls.py 中更新用户名类型

有帮助,但不是必需的。

网址.py

path('<slug:username>/', UserProfileDetailView.as_view(), name = 'detail'),

引用资料

Django 详细 View get_slug_field (Github):https://github.com/django/django/blob/master/django/views/generic/detail.py#L78-L80

关于python - 通用详细 View UserProfileDetailView 必须使用对象 pk 或 URLconf 中的 slug 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64303253/

相关文章:

python - 有条件地过滤一个 df 中的行以获取另一个 df 的子集共有的特定列

django - 模型妈妈 : Multiple recipes with foreign key relation to a single recipe

django - Django ManyToMany 字段的 set() 操作是否清除现有关系?

python - 使用 Docker 使用 Django 创建 mysql 数据库

Python,删除UTF8 MySQL DB无法处理的字符,例如表情符号

python - 无法让 django dashing 示例工作

python - 向 pandas 数据框添加一列会用 NA 填充它

python - 在南方,我可以将旧列的值复制到新列吗?

python - 具有多个模型的外键

mysql - 在主键以外的字段上加入另一个表