通用详细信息视图UserProfileDetailView必须使用URLconf中的对象pk或slug调用 [英] Generic detail view UserProfileDetailView must be called with either an object pk or a slug in the URLconf

查看:123
本文介绍了通用详细信息视图UserProfileDetailView必须使用URLconf中的对象pk或slug调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我面临错误,现在这个问题已经过去了两天,仍然停留在这个错误上,任何人都可以帮助并且能够解决这个问题。我是Django的新手,需要帮助。我会很感激的。如果有其他事情需要答案而不是告诉我,我将用详细信息更新我的问题。.
models.py

Well I am facing error and it's now its been two days to this question and still stuck on this mistake, anybody can help and able to fix this. I am new in Django and need help. I shall be thankful. If any thing else requires for answers than tell me I will update my questions with that detail.. models.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}'

views.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

urls.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

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 %}

snippets / follow_toggle.html

snippets/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.


推荐答案

问题


    使用
  1. str 类型代替urls.py
  2. $中的 slug 类型b $ b
  3. UserProfileDetailView 没有指定自定义 slug_url_kwarg slug_field

  4. UserProfileDetailView 指定 UserProfile 模型,但 UserProfile 模型没有属性或方法用户名,位于用户表中。

  1. str type used instead of slug type in urls.py
  2. UserProfileDetailView doesn't specify your custom slug_url_kwarg and slug_field
  3. UserProfileDetailView specifies UserProfile model but UserProfile model doesn't have attribute or method username, which is on `User table.


解决方案


阅读Django的DetailView代码,您将发现以下内容对于使代码正常工作是必要的。

Solution

Reading Django's DetailView code, you'll find that the following is necessary to get your code working properly.

views.py

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


更新UserProfile模型或更新UserProfileDetailView.get_slug_field


UserProfile是为UserProfileDetailView和 get_slug_field 方法定义的查找表,该方法在UserProfileDetailView上读取 slug_field 属性不支持点语法方法遍历(即: user.username`)。
因此,要么:

Update UserProfile model OR Update UserProfileDetailView.get_slug_field

UserProfile is the lookup table defined for UserProfileDetailView and get_slug_fieldmethod, which readsslug_fieldproperty on the UserProfileDetailView doesn't support dot syntax method traversal (ie:user.username`). Thus either:


  1. UserProfile模型必须引用用户名或;

  2. get_slug_field 必须显式定义子域或;

  3. get_slug_field 必须为点语法方法遍历添加功能

  1. UserProfile model must have reference to username or;
  2. get_slug_field must explicitly define slug field or;
  3. get_slug_field must add functionality for dot syntax method traversal

models.py

models.py

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

OR

class UserProfileDetailView(DetailView):
    ...

    def get_slug_field(self):
        self.user.username


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


有用,但不是必需的。

Update username type in urls.py

Helpful, but not necessary.

urls.py

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


参考


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

References

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

这篇关于通用详细信息视图UserProfileDetailView必须使用URLconf中的对象pk或slug调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆