edit and update the row in database using django

两盒软妹~` 提交于 2019-12-10 12:19:12

问题


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

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

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

urls.py is

admin.autodiscover()

urlpatterns = patterns('',
    url('^$', index),
    url('^index/$', index),
    url('^addbook/$', addbook),
    url('^book_detail/$', book_detail, 'book_summary'),
    url('^editbook/(?P<book_id>\d+)/$', editbook) ,
    url('^deletebook/(?P<book_id>\d+)/$',deletebook) ,


    url(r'^admin/', include(admin.site.urls)),


)

I need to perform edit and update the row in database,i did it by using single table.But using two table have some confusion how to take 2nd table using that particular id.I am using forms in this.Can you help me in this to write codes in views.py.Example for doing the same using two table is no where i seen.

Thanks


回答1:


def update_book(request, book_id):
    author = get_object_or_404(Author, pk=author_id)

    form = AuthorForm(instance=author)
    book_formset = BookFormset(instance=author)

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

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


<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>


来源:https://stackoverflow.com/questions/15403179/edit-and-update-the-row-in-database-using-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!