【发布时间】:2021-01-25 21:43:18
【问题描述】:
好吧,我遇到了错误,现在这个问题已经两天了,仍然坚持这个错误,任何人都可以提供帮助并能够解决这个问题。我是 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}'
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
{% 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 %}
sn-ps/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.
【问题讨论】:
-
能否也添加您的用户模型的定义?
-
我正在使用来自
djnago.contrib.auth.models import User的django内置用户模型 -
对不起,我的意思是 UserProfile 模型。在这种情况下,我假设 UserProfile 与
User实例具有 OneToOneuser关系?如果是这样,请查看 docs.djangoproject.com/en/3.1/topics/db/examples/one_to_one 以及如何捕获 RelatedObjectDoesNotExist 异常。 -
是的,userprofile 与用户模型是一对一的关系
-
那就这样吧。您可能在没有为
user设置关系的情况下创建了 UserProfile 实例。我建议将其设为不可为空的字段 (null=False, blank=False) 以防止这种情况发生 - 没有 User 的 UserProfile 真的没有意义吗?
标签: python django django-models django-views django-templates