django form 验证

做一个article 的app

class Article(models.Model):
    author = models.ForeignKey(User, verbose_name=_('User'))
    subject = models.CharField(max_length=250,verbose_name=_('Subject'))
    content = models.TextField(verbose_name=_('Content'))


class ArticleForm(ModelForm):
subject = forms.CharField(label=_("subject"), required=True)
content = forms.CharField(widget=forms.Textarea)

class Meta:
    model = Article
    list = ('subject','content','author')我们会看到author是一个外键来的,这个外键要从session中得到的。

所以看下面的示例代码 :


def add(request):
    context ={}
    context['article_form'] = ArticleForm()
   
    if request.method == 'POST':
        #save the author automatic
        article_form = ArticleForm(request.POST)  
        if article_form.is_valid():
            article_form.save()如果按上面那样写,是无法通过验证的。因为这个时候传输过来的author是空的。

那怎么处理呢?


def add(request):
    context ={}
    context['article_form'] = ArticleForm()
   
    if request.method == 'POST':
        #save the author automatic
        post_values = request.POST.copy()
        post_values['author'] = request.juser.pk
        article_form = ArticleForm(post_values)  
        if article_form.is_valid():
            article_form.save()

 

你可能感兴趣的:(django form 验证)