(Django)不能分配&#34; <article:>&#34;:&#34; Article.user&#34;必须是&#34;用户&#34;实例</文章:>

时间:2015-03-20 21:15:24

标签: python django forms

我提交表单时收到错误。

Cannot assign "Article": : "Article.user" must be a "User" instance. 

我在Django没有那么老,我可以看到存在用户实例问题。我该如何解决这个问题?

以下是模型:

from django.db import models
from updown.fields import RatingField
from taggit.managers import TaggableManager
from taggit.models import *
from django.db.models.signals import pre_delete
from django.contrib.auth.models import User

class Article(models.Model):
    user = models.OneToOneField(User)
    titre = models.CharField(max_length=100)
    contenu = models.TextField(null=True)
    date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de parution")
    image = models.ImageField(upload_to='article', default='article/amazarashi.jpeg')
    rating = RatingField(can_change_vote=True)
    tags = TaggableManager(through=TaggedItem, blank=True)

    def __str__(self):
        return self.titre

以下是表格:

class ArticleForm(forms.ModelForm):

    class Meta:
        model = Article
        exclude = ['date', 'rating', 'user']

        widgets={
            "titre":forms.TextInput(attrs={'placeholder':'Le titre', 'class':'form-control'}),
            "contenu":forms.Textarea(attrs={'placeholder':'Le Contenu de votre message','class':'form-control'}),
            "image":forms.FileInput(attrs={'id':'uploadBtn', 'placeholder':'Votre Image', 'class':'form-control'}),
            "tags":forms.TextInput(attrs={'placeholder':'Vos Tags', 'class':'form-control'}),
        }  

form = ArticleForm()

以下是视图:

@login_required
def AddArticle(request):
    form = ArticleForm(request.POST, request.FILES)

    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.user = Article(user=request.user)
        save_it.save()

    context = { 'form':form }
    populateContext(request, context)
    return render(request, 'addarticle.html', context)

1 个答案:

答案 0 :(得分:0)

在那一部分,您将文章作为用户

if form.is_valid():
    save_it = form.save(commit=False)
    save_it.user = Article(user=request.user)
    save_it.save()

正确的方法是:

if form.is_valid():
    save_it = form.save(commit=False)
    save_it.user = request.user
    save_it.save()