Wednesday, April 6, 2016

Working with multiple modelform using single view in django.

#models.py

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

def __str__(self):
        return self.name

class Article(models.Model):
    title = models.CharField(max_length=100)
    pub_date = models.DateField()
    email = models.EmailField(unique=True)
    author = models.ForeignKey(Author)

    def __str__(self):
        return self.title

# forms.py
from django.forms import formset_factory
from django.forms import ModelForm
from .models import Article, Author


class ArticleForm(ModelForm):
    class Meta:
        model = Article
        fields = ['email', 'title', 'pub_date']


class AuthorForm(ModelForm):
    class Meta:
        model= Author
        fields = ['name']

#views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import ArticleForm, AuthorForm
from .models import Article, Author

def index(request):
    forms = {}
    forms['article_form'] = ArticleForm(prefix='article')
    forms['author_form']  = AuthorForm(prefix='author')
    if request.method == 'POST':
        article_form = ArticleForm(request.POST, prefix='article')
        author_form = AuthorForm(request.POST, prefix='author')


        if article_form.is_valid() and author_form.is_valid():
            article = article_form.save(commit=False)
            author = author_form.save()
            print(author.id)
            article.author = author

            article.save()


            return HttpResponse("Thank you")

        else:
            forms['article_form']  = article_form
            forms['author_form'] = author_form
            return render(request,'index.html', forms)


    else:
        return render(request,'index.html', forms)

No comments:

Post a Comment