使用django将数据保存到数据库

时间:2021-07-13 07:40:56

views.py

views.py

def addbook(request): 
    if request.POST:
        book_form = BookForm(request.POST)
    author_form = AuthorForm(request.POST)
        if (book_form.is_valid() and author_form.is_valid()):
        log.debug("test....")
            book=book_form.save()
            author=author_form.save()
        author.book=book
        author.save()

        return redirect('/index/')
    else:
    book_form=BookForm()
        author_form=AuthorForm()
        return render_to_response('addbook.html',{'form':book_form,'form':author_form},context_instance=RequestContext(request))

forms.py

forms.py

from django import forms
from django.forms import ModelForm
from myapp.models import Book,Author


class AuthorForm(ModelForm):

    class Meta:
        model = Author

        fields=['author_id','first_name','last_name','email','age']        


class BookForm(ModelForm):

    class Meta:
        model = Book

        fields=['book_id','book_name','publisher_name','author']        

models.py

models.py

from django.db import models

class Author(models.Model):
    author_id = models.AutoField(primary_key=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age=models.IntegerField()

    class Meta:
    db_table=u'Author'

    def __unicode__(self):
        return u"%d %s %s %s %d" % (self.pk, self.first_name, self.last_name, self.email,self.age)


class Book(models.Model):
    book_id=models.AutoField(primary_key=True,unique=True)
    book_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    author=models.ForeignKey(Author)

    class Meta:
        db_table = u'Book'

    def __unicode__(self):
        return u'%d %s %s' % (self.pk, self.book_name, self.publisher_name)

templates.html

templates.html

<div align="center">

  <form action="/addbook/" method="post">
     {% csrf_token %}
    {{ book_form.as_p }}
    {{ author_form.as_p }}
    <input type="submit" value="submit">
    </form>

Here I am using author as foriegnkey.In form,I had given fields for all the fields in database.When I click the submit button it is showing the fields,along with author field. Here author_id in author table is pointing the author_id in book table.In views.py how we can implement that.

在这里,我使用作为foriegnkey的作者。在表单中,我为数据库中的所有字段提供了字段。当我单击提交按钮时,它显示字段以及作者字段。这里作者表中的author_id将author_id指向book表。在views.py中我们如何实现它。

I am expecting to save the data into database in this way.I changed my template also.

我希望以这种方式将数据保存到数据库中。我也改变了我的模板。

1 个解决方案

#1


11  

models.py

models.py

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age = models.IntegerField()

    def __unicode__(self):
        return "{0} {1} {2} {3} {4}".format(
            self, self.first_name, self.last_name, self.email, self.age)

class Book(models.Model):
    book_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    author=models.ForeignKey(Author)

    def __unicode__(self):
        return "{0} {1} {2}".format(
            self.pk, self.book_name, self.publisher_name)

forms.py

forms.py

class AuthorForm(ModelForm):
    class Meta:
        model = Author     

BookFormset = inlineformset_factory(Author, Book, 
    fields=('book_name', 'publisher_name'), extra=1, 
    can_delete=False) 

views.py

views.py

def addbook(request):
    form = AuthorForm()
    book_formset = BookFormset(instance=Author())

    if request.POST:
        form = AuthorForm(request.POST)
        if form.is_valid():
            author = form.save()
            book_formset = BookFormset(request.POST, instance=author)
            if book_formset.is_valid():
                book_formset.save()
            return redirect('/index/')

    return render_to_response('addbook.html',{
        'form': form, 'formset': book_formset
    },context_instance=RequestContext(request))  

template

模板

<div align="center">
    <tr>
        <form method="POST"> 
            {% csrf_token %} 
            <h5>Author:</h5>
            {{ form.as_p }}

            <h5>Book:</h5>
            {{ formset.as_p }}
            <input type="submit" value="submit">
        </form>
    </tr>
</div>

#1


11  

models.py

models.py

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age = models.IntegerField()

    def __unicode__(self):
        return "{0} {1} {2} {3} {4}".format(
            self, self.first_name, self.last_name, self.email, self.age)

class Book(models.Model):
    book_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    author=models.ForeignKey(Author)

    def __unicode__(self):
        return "{0} {1} {2}".format(
            self.pk, self.book_name, self.publisher_name)

forms.py

forms.py

class AuthorForm(ModelForm):
    class Meta:
        model = Author     

BookFormset = inlineformset_factory(Author, Book, 
    fields=('book_name', 'publisher_name'), extra=1, 
    can_delete=False) 

views.py

views.py

def addbook(request):
    form = AuthorForm()
    book_formset = BookFormset(instance=Author())

    if request.POST:
        form = AuthorForm(request.POST)
        if form.is_valid():
            author = form.save()
            book_formset = BookFormset(request.POST, instance=author)
            if book_formset.is_valid():
                book_formset.save()
            return redirect('/index/')

    return render_to_response('addbook.html',{
        'form': form, 'formset': book_formset
    },context_instance=RequestContext(request))  

template

模板

<div align="center">
    <tr>
        <form method="POST"> 
            {% csrf_token %} 
            <h5>Author:</h5>
            {{ form.as_p }}

            <h5>Book:</h5>
            {{ formset.as_p }}
            <input type="submit" value="submit">
        </form>
    </tr>
</div>