当我尝试将作者或用户分配给帖子时,Django会发出以下错误:
Cannot assign "<User: henrydavidzhu>": "Post.author" must be a "User" instance.
这是我的views.py:
user_passes_test(lambda u: u.is_authenticated)
def add_post(request):
form = PostForm(request.POST or None)
print("User: " + str(request.user))
if form.is_valid() and request.user.is_authenticated():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect(post)
else:
print(form.errors)
return render_to_response('webapp/startthread.html',
{ 'form': form },
context_instance=RequestContext(request))
这是我的forms.py:
class PostForm(forms.ModelForm):
CHOICES = (
('Hardware and OS', ' Desktops'),
)
field = forms.ChoiceField(choices=CHOICES)
class Meta:
model = Post
exclude = ['author', 'slug']
这是我的models.py:
class Post(models.Model):
title = models.CharField(max_length=500)
slug = models.SlugField(unique=True)
text = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, unique=True)
def __unicode__(self):
return self.title
@models.permalink
def get_absolute_url(self):
return ('blog_post_detail', (),
{
'slug' :self.slug,
})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
答案 0 :(得分:0)
我不得不改变以下内容:
author = models.ForeignKey(User)
到此:
author = models.ForeignKey('auth.User')
答案 1 :(得分:0)
我正在使用django 1.8,你的代码对我有用。
如果您的站点已登录,request.user
将为用户实例提供
例如:
print request.user