本文介绍了在modelforms中的valueError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用模型来获取播放列表及其项目。它还包含登录脚本。我正在尝试将当前登录的用户设置为用户模型。
您可以看到我之前发布的这个东西

I'm using modelforms for getting playlist and its items. It also contains login script. I'm trying to set the currently logged in user to the user model.You can see this thing I've posted beforeHow 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'}

这是播放列表视图:

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文件:

Playlist.html file:

错误页面:

但我正在获得 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

Here is my settings.pyhttps://gist.github.com/1575856

谢谢。 p>

Thank you.

推荐答案

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

I know this post is old, but if anyone gets here with the same problem, the answer is that request.user is actually a wrapper for django's auth.user.So request.user is a SimpleLazyObject, and it's purpose is avoiding unnecessary instantiation, and also implementing a simple user caching mechanism.To access the actual user (and instantiate it, when accessing the first time), you need to do:

auth.get_user (请求)

这将给你一个 auth.user 的实例。
如果您需要有关内部发生的更多细节,请参阅。

This will give you an instance of auth.user.If you need more detail on what's going on inside, see this post.

这篇关于在modelforms中的valueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 01:17