Django - 从多个模型中保存表单

时间:2014-06-12 19:53:21

标签: django django-forms

我是Django的新手,并试图创建一个简单的博客平台。用户可以在前端创建/编辑博客文章。

这是我的models.py

 class Blog(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    author = models.ForeignKey(User, null=True, blank=True)
    ......

 class Categories(models.Model):
    blog = models.ForeignKey(Blog)
    name = models.CharField(max_length=200)
    slug = models.CharField(max_length=200)
    ......

我在前端创建了一个表单:

#forms.py
class AddBlogForm(forms.ModelForm):

    class Meta:
        model = Blog

class AddCategoryForm(forms.ModelForm):

    class Meta:
        model = Categories

 #views.py
 def AddBlogPost(request):
    if request.POST:
      lf= AddBlogForm(request.POST, request.FILES,prefix="Lform")
      cf = AddCategoryForm(request.POST, prefix="Cform")
    if lf.is_valid() and cf.is_valid():
        addblog =  lf.save(commit=False)
        addblog.save()
        obj_id = addblog.id

        addcategory = cf.save(commit=False)
        addcatgory.blog_id = obj_id
        addcatgory.save()


    return HttpResponseRedirect(reverse('edit', args=(obj_id,)))


else:
      blog= AddBlogForm(prefix="Lform")
      category = AddCategoryForm(prefix="Cform")
    return render_to_response("forms.html", locals(),context_instance=RequestContext(request))

 #template 
 <form action="" enctype="multipart/form-data" method="POST">{% csrf_token %}
    {{blog.as_p}}
    {{category.as_p}}
    <input type="submit">
  </form>

这实际上是有效的,但是我觉得创建和保存带有两个类的表单太多了。但是还有什么可以简化这个?

1 个答案:

答案 0 :(得分:1)

您可以使用django表单将表单中的数据保存到多个模型。例如:

forms.py

class AddBlogCategory(forms.Form):
    title= form.CharField(max_length=100)
    content= form.CharField(max_length=255)
    ...............
    ...............

views.py:

def AddBlogPost(request):
   if request.POST:
      form= AddBlogCategory(request.POST)
       if form.is_valid():
          addblog= Blog() #import model class
          addblog.title= form.cleaned_data['title']
          addblog.content= form.cleaned_data['content']
          addblog.author= request.user
          .....
          addblog.save()
          obj_id= addblog.id

          addcat=Categories()
          addcat.blog= addblog
          ....
          addcat.save()

          return HttpResponseRedirect(reverse('edit', args=(obj_id,)))
      else:
          return render_to_response("forms.html", {form:'form'})

它是一个未经测试的代码,但你可以知道如何实现它。