/ posts / create /中的ValueError无法分配&#34; <blogpost:india =“”>&#34;:&#34; BlogPost.owner&#34;必须是&#34;用户&#34;例

时间:2016-07-23 11:05:10

标签: django

class BlogPost(models.Model):
    owner = models.ForeignKey(User, null=True, blank=True)
    title = models.CharField(max_length=120)
    slug = models.SlugField(max_length=500, editable=False)
    image = models.ImageField(upload_to=upload_location, 
            null=True, 
            blank=True, 
            width_field="width_field", 
            height_field="height_field")
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    content = models.TextField()
    draft = models.BooleanField(default=False)
    publish = models.DateField(auto_now=False, auto_now_add=False)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    is_shared = models.BooleanField(default=False, verbose_name='Share')

    objects = PostManager()

    def __unicode__(self):
        return str(self.title)

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"slug": self.slug})

views.py

class NewBlogPostView(CreateView):
    form_class = BlogPostForm
    template_name = 'post_form.html'

    def dispatch(self, request, *args, **kwargs):
        return super(NewBlogPostView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        blog_post_obj = form.save(commit=False)
        blog_post_obj.owner = BlogPost.objects.get(owner=self.request.user)
        blog_post_obj.save()
        return HttpResponseRedirect(blog_post_obj.get_absolute_url())

管理员

class BlogPostAdmin(admin.ModelAdmin):
    list_display = ('title', 'content')

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'owner', None) is None:
            obj.owner = request.user
        obj.save()

admin.site.register(BlogPost, BlogPostAdmin)

我想为该网站拥有多个用户,现在我收到如下错误

  

/ posts / create /的ValueError   无法分配&#34;&#34;:&#34; BlogPost.owner&#34;必须是&#34;用户&#34;实例

0 个答案:

没有答案