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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With