【问题标题】:Exception Type: DoesNotExist | Profile matching query does not exist异常类型:DoesNotExist |配置文件匹配查询不存在
【发布时间】:2021-04-18 16:50:55
【问题描述】:

我试图在 URL 模式中获取用户名而不是 id <a class="dropdown-item" href="{% url 'UserApp:profile' username=profile.username%}">Profile</a>,因此在注销功能中出现错误:配置文件匹配查询不存在。但是配置文件模板正在渲染将所有查询都没有任何错误。如果我在 URL 中也使用 id 一切正常!请向我建议如何摆脱错误。谢谢!

Views.py

def logout_view(request):
    logout(request)
    return redirect("index")


@login_required
def profile(request, username):
    title = 'Profile'
    context={'title': title}
    profile = Profile.objects.get(username=username)
    if profile:
        context.update(profile = profile)
    else:
        return HttpResponse("user is not found")
    return render(request, 'UserApp/profile.html', context)

Urls.py

from django.urls import path
from UserApp import views

app_name = 'UserApp'

urlpatterns = [
    path('<str:username>/', views.profile, name='profile'),
    path('signup/', views.signup, name='signup'),
    path('login/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
    path('update/', views.update_profile, name='update'),
]

我使用 BaseUserManager、AbstractBaseUser 进行用户注册和客户档案模型来获取用户名

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    username = models.CharField(max_length=264, null=True, blank=True)
    full_name = models.CharField(max_length=264, blank=True)
    address_1 = models.TextField(max_length=300, blank=True)
    city = models.CharField(max_length=40, blank=True)
    zipcode = models.CharField(max_length=10, blank=True)
    country = models.CharField(max_length=50, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    pro_pic = models.ImageField(upload_to=None, blank=True)
    about = models.CharField(max_length=500, blank=True)

    def __str__(self):
        return self.username

    def is_fully_filled(self):
        fields_names = [f.name for f in self._meta.get_fields()]

        for field_name in fields_names:
            value = getattr(self, field_name)
            if value is None or value == '':
                return False
        return True

终端出错

  File "C:\Users\SONJOY\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\SONJOY\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "D:\TrackingSystem\UserApp\views.py", line 49, in profile
    profile = Profile.objects.get(username=username)
  File "C:\Users\SONJOY\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\SONJOY\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 429, in get
    raise self.model.DoesNotExist(
UserApp.models.Profile.DoesNotExist: Profile matching query does not exist.
[15/Apr/2021 09:52:47] "GET /user/logout/ HTTP/1.1" 500 77227

【问题讨论】:

  • 你能确认一下 profile.username 的值吗?也是 L49 视图中用户名的值,在 profile()
  • 我解决了这个问题,上面的答案帮助我解决了所有问题

标签: django django-models django-rest-framework django-views


【解决方案1】:

如果您访问/logout url,它将匹配profile 视图,因为这是匹配的第一个url 模式。你应该把它放在最后,这样signuploginlogout等视图首先匹配,只有当这些失败时,你“解雇”profile视图,所以:

from django.urls import path
from UserApp import views

app_name = 'UserApp'

urlpatterns = [
    path('signup/', views.signup, name='signup'),
    path('login/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
    path('update/', views.update_profile, name='update'),    
    # put this last &downarrow;
    path('<str:username>/', views.profile, name='profile'),
]

【讨论】:

  • 最好在 url 模式中添加前缀或后缀:user/&lt;str:username&gt;/。这使您的网址提供更多信息,防止这种情况,通常更好。
  • 感谢您的帮助,对延误表示歉意。您的解决方案运行良好,我还没有遇到任何问题.. 遵循这个技巧。
猜你喜欢
  • 2022-01-08
  • 1970-01-01
  • 2022-01-10
  • 2013-07-27
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多