python - 模型中的值错误

标签 python django django-models django-forms

我正在使用模型来获取播放列表及其项目。它还包含登录脚本。我正在尝试将当前登录的用户设置为用户模型。 你可以看看我之前发过的这个东西 How to avoid this dropdown combo box?

class playlistmodel(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=200)

    def __unicode__(self):
        return self.title

class itemsmodel(models.Model):
    playlist = models.ForeignKey(playlistmodel)
    item = models.TextField()

    def __unicode(self):
        return self.item

class playlistform(ModelForm):
    class Meta:
        model = playlistmodel
        exclude = {'user'}

class itemsform(ModelForm):
    class Meta:
        model = itemsmodel
        exclude = {'playlist'}

这是播放 ListView :

def playlistview(request):
    if request.method == 'POST':
        form = playlistform(request.POST)
        if form.is_valid():
                data = form.save(commit=False)
                data.user = request.user
                data.save()
                return render_to_response('playlist.html', {'data': data})
    else:
        form = playlistform()
        return render_to_response('playlist.html', {'form': form, 'user': request.user}, context_instance=RequestContext(request))

Playlist.html 文件:

https://gist.github.com/1576136

错误页面:

https://gist.github.com/1576186

但是我得到了 ValueError:

Exception Type: ValueError Exception Value: Cannot assign "<django.utils.functional.SimpleLazyObject object at 0x7f0234028f50>": "playlistmodel.user" must be a "User" instance

Traceback: Local vars --- data.user = request.user

这是我的settings.py https://gist.github.com/1575856

谢谢。

最佳答案

我知道这篇文章很旧,但如果有人遇到同样的问题,答案是 request.user 实际上是 django 的 auth.user 的包装器. 所以request.user是一个SimpleLazyObject,它的目的是避免不必要的实例化,同时实现一个简单的用户缓存机制。 要访问实际用户(并在第一次访问时实例化它),您需要执行以下操作:

auth.get_user(请求)

这将为您提供 auth.user 的实例。 如果您需要有关内部情况的更多详细信息,请参阅 this post .

关于python - 模型中的值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8770403/

相关文章:

python - pytz 和 Centos 以及 mysql - django

django-allauth 没有名为 'django.core.email' 的模块

python - python cgi 和 python django 之间的单点登录

django - 在 Celery 任务中使用 Django 的 ORM

Django:使用模型保存保存用户 ID

python - 在库 libxml2 中找不到函数 xmlCheckVersion。是否安装了 libxml2?错误 : command 'gcc' failed with exit status 1

python - OpenCV Python : How to overlay an image into the centre of another image

python - 在 django admin 中创建对象时如何自动插入当前用户?

python - 使用函数修改数据表 UserProfile 中的值

python - Django 中的 ModelForms 与 ManyToMany 关系模型