问题描述
好吧,我遇到了错误,现在这个问题已经过去两天了,但仍然坚持这个错误,任何人都可以提供帮助并能够解决这个问题.我是 Django 的新手,需要帮助.我会很感激的.如果还有什么需要回答而不是告诉我,我会用那个细节更新我的问题.模型.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:UsersAHMEDanaconda3libsite-packagesdjangocorehandlersexception.py", line 34, in inner
response = get_response(request)
File "C:UsersAHMEDanaconda3libsite-packagesdjangocorehandlersase.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:UsersAHMEDanaconda3libsite-packagesdjangocorehandlersase.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersAHMEDanaconda3libsite-packagesdjangoviewsgenericase.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:UsersAHMEDanaconda3libsite-packagesdjangoviewsgenericase.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:UsersAHMEDanaconda3libsite-packagesdjangoviewsgenericdetail.py", line 106, in get
self.object = self.get_object()
File "C:UsersAHMEDanaconda3libsite-packagesdjangoviewsgenericdetail.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.
推荐答案
问题
- 使用
str
类型代替 urls.py 中的slug
类型UserProfileDetailView
未指定您的自定义slug_url_kwarg
和slug_field
UserProfileDetailView
指定了UserProfile
模型,但UserProfile
模型没有属性或方法username
,这是在`用户表.
str
type used instead ofslug
type in urls.pyUserProfileDetailView
doesn't specify your customslug_url_kwarg
andslug_field
UserProfileDetailView
specifiesUserProfile
model butUserProfile
model doesn't have attribute or methodusername
, 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_fieldmethod 定义的查找表,它读取
slug_field 在 UserProfileDetailView 上的属性不支持点语法方法遍历(即:
user.username`).因此要么:
Update UserProfile model OR Update UserProfileDetailView.get_slug_field
UserProfile is the lookup table defined for UserProfileDetailView and
get_slug_fieldmethod, which reads
slug_fieldproperty on the UserProfileDetailView doesn't support dot syntax method traversal (ie:
user.username`).Thus either:
- UserProfile 模型必须引用
username
或; get_slug_field
必须明确定义 slug 字段或;get_slug_field
必须添加点语法方法遍历的功能
- UserProfile model must have reference to
username
or; get_slug_field
must explicitly define slug field or;get_slug_field
must add functionality for dot syntax method traversal
models.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 中的用户名类型
有帮助,但不是必需的.
Update username type in urls.py
Helpful, but not necessary.
urls.py
path('<slug:username>/', UserProfileDetailView.as_view(), name = 'detail'),
参考文献
Django 详细视图 get_slug_field
(Github):https://github.com/django/django/blob/master/django/views/generic/detail.py#L78-L80
这篇关于必须使用 URLconf 中的对象 pk 或 slug 调用通用详细信息视图 UserProfileDetailView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!