我的Django应用程序中有一个方法,它使用用户ID来查找对象。通过AJAX调用调用此方法。登录到有效的用户帐户后,无论我尝试什么,request.user
都会评估为django.utils.functional.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 + ".";
}
在维护会话信息的请求中是否需要设置一些内容?在早期版本的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)
答案 0 :(得分:0)
正如rohan所说,你不需要使用user.pk
更改此查询
entry = SkillEntry.objects.get(user=user.pk, skill=skill)
TO
entry = SkillEntry.objects.get(user=user, skill=skill)
如果不能正常工作,请分享您的models.py