【问题标题】:Django model object query misbehavingDjango模型对象查询行为不端
【发布时间】:2021-05-22 02:57:15
【问题描述】:

我正在尝试显示配置文件的内容,该配置文件是链接到内置用户模型的模型。一切正常,奇怪的是除了模型的最后一个对象条目。例如,如果 user8 是使用 user1 登录到用户 7 的最后一个模型对象,则正在使用已验证属于当前用户的所有内容。但是当我使用最后一个对象登录时,即。 user8 在这种情况下我得到一个 Page 404 not found : No (Model name) 匹配给定的查询错误。更清楚一点,现在如果我创建另一个名为 user9 的用户,现在我可以使用 user8 登录,但不能使用最后创建的 user9 登录。

**views.py : **

# Create your views here.
def home(request):
    

    if request.user.is_authenticated:
        contextvar = Post.objects.all()
        user_content = get_object_or_404(user_profile, pk = request.user.pk)
        
        # user_content = user_profile.objects.get(pk=request.user.pk)
        # user_content = user_profile.objects.get(pk='8')
        print("the current users id is " , request.user.pk)
        return render(request,'homepage.htm', {'context':contextvar , 'user_content' : user_content ,  "up" : request.user.pk })
        
    else:
        contextvar = Post.objects.all()
        return render(request,'homepage.htm', {'context':contextvar})

models.py:

from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class user_profile(models.Model): 
    #using default User model by linking 
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    #additional fields
    website = models.URLField(blank=True)
    profile_picture = models.ImageField(upload_to='profile_pictures' , blank = True )
    bio = models.CharField(blank=True, max_length=300)
    
    def __str__(self):
        return (self.user.username + " " +  str(self.user.id))

页面错误:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/
Raised by:  blog.views.home
No user_profile matches the given query.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

如果您需要查看其他内容,请告诉我...谢谢

【问题讨论】:

    标签: django django-models django-views django-queryset django-orm


    【解决方案1】:

    它不应该正常运行,因为您正在使用用户的主键查询用户配置文件。老实说,您不需要它,因为您可以通过以下方式获取用户配置文件:

    user_profile = request.user.user_profile
    

    由于User 和user_profile 模型之间的OneToOne 关系。

    仅供参考,根据pep-8 style guide,类名应为 PascalCase。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2021-12-25
      • 2012-03-25
      • 2017-08-10
      • 2015-07-13
      • 1970-01-01
      相关资源
      最近更新 更多