gpt4 book ai didi

javascript - Django request.user 无法解析 SimpleLazyObject

转载 作者:行者123 更新时间:2023-11-28 09:17:36 25 4
gpt4 key购买 nike

我的 Django 应用程序中有一个方法,它使用用户 ID 来查找对象。该方法通过 AJAX 调用来调用。登录到有效的用户帐户时,无论我尝试什么,request.user 都会将其计算为 django.utils.function.SimpleLazyObject 对象,并且无法检索我的数据想要(SkillEntry 匹配查询不存在,当它绝对存在时)。我尝试了Django: Filtering drafts by user causes error中的解决方案没有效果。

如何让用户引用用户对象的实际实例?

查看代码:

@login_required
def skill_set(request, name):
skill = Skill.objects.get(slug=name) # Found.
level = 0
user = request.user
if request.method == 'POST':
if user.is_authenticated():
entry = SkillEntry.objects.get(user=user.pk, skill=skill) # Not found.
entry.level = request.POST['level']
entry.save()
return HttpResponse(status=200)
else:
return HttpResponseForbidden()

JavaScript 客户端代码:

function setSkill(skill, value) {
var req = new XMLHttpRequest();
req.open("POST", "/skill/" + skill + "/set/", true);
csrftoken = getCookie('csrftoken');
req.setRequestHeader("X-CSRFToken", csrftoken);
req.send('level=' + value);
var elem = document.getElementById('level');
elem.innerHTML = "My skill level is " + value + ".";
}

我是否需要在请求中设置一些内容来维护 session 信息?我可以发誓我以前在 Django 的早期版本上成功地做过类似的事情。我使用的是 1.4.3。

编辑:

以下是我的 models.py 中的模型定义:

class Skill(models.Model):
name = models.CharField(max_length=100)
slug = models.CharField(max_length=100, blank=True)
keywords = models.CharField(max_length=120, blank=True, help_text='List of additional keywords this skill should show up for in search')
description = models.TextField(null=True, blank=True)
parent = models.ForeignKey('Skill', null=True, blank=True, help_text='Parent skill. Leave blank if this is a root category.')

def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.name)
super(Skill, self).save(*args, **kwargs)

def __unicode__(self):
return self.name

class Meta:
ordering = ('name',)

class SkillEntry(models.Model):
skill = models.ForeignKey('Skill')
level = models.IntegerField()
user = models.ForeignKey(User)
last_updated = models.DateField(auto_now=True)

class Meta:
verbose_name_plural = 'Skill Entries'
ordering = ('skill__name',)

def __unicode__(self):
return self.user.username + ' knows ' + self.skill.name + ' at level ' + str(self.level)

最佳答案

正如罗汉所说,你不需要使用user.pk

更改此查询

entry = SkillEntry.objects.get(user=user.pk, skill=skill) 

    entry = SkillEntry.objects.get(user=user, skill=skill) 

如果它不起作用,请分享您的 models.py

关于javascript - Django request.user 无法解析 SimpleLazyObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15446126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com