我的 Django 应用程序中有一个使用用户 ID 查找对象的方法。此方法通过 AJAX 调用调用。当登录到有效的用户帐户时,无论我尝试什么,都会request.user
评估为一个django.utils.functional.SimpleLazyObject
对象并且无法检索到我想要的数据(SkillEntry 匹配查询绝对存在时不存在)。我在 Django 中尝试了解决方案:按用户过滤草稿导致错误无济于事。
如何让用户引用用户对象的实际实例?
查看代码:
@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)