Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

valueError in modelforms

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 before 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'}

Here is the playlist view:

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 file:

https://gist.github.com/1576136

Error Page:

https://gist.github.com/1576186

But I'm getting 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

Here is my settings.py https://gist.github.com/1575856

Thank you.

like image 488
rnk Avatar asked Jan 07 '12 14:01

rnk


1 Answers

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(request)

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

like image 162
Anoyz Avatar answered Oct 22 '22 15:10

Anoyz