使用django编辑和更新数据库中的行 [英] edit and update the row in database using django

查看:155
本文介绍了使用django编辑和更新数据库中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

urls.py是

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


)

我需要执行编辑和更新数据库中的行,我做了它使用单个表。但是使用两个表有一些混淆如何使用第二个表使用该特定的id.I使用的形式在这。可以帮助我在这里编写代码在views.py.Example做同样的使用两张桌子是我看不到的。

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.

谢谢

推荐答案

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>

这篇关于使用django编辑和更新数据库中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆