真的骄傲梦想家园
专业源于兴趣和努力

新建一个ceshi的应用(app),功能是开发一个心理测试系统,后台增加测试(ceshi),点保存的时候需要跳转到增加问题(question)的界面,然而默认的操作没有这个功能,需要重写admin.ModelAdmin的response_add方法,重写的代码如下:

 

class CeshiAdmin(admin.ModelAdmin):
    fields = ('type', 'title', 'content', 'cover', 'tags')
    
    def response_add(self, request, obj, post_url_continue='../%s/'):
        path = 'http://www.cnblogs.com/ceshijumpquestion/add/?ceshi_id=%s' % obj._get_pk_val()
        super(CeshiAdmin, self).response_add(request, obj, post_url_continue=post_url_continue)
        return HttpResponseRedirect(path)

  

调用父类的方法,然后重定向到我们需要的地址,这样,增加ceshi后页面就会跳转到增加question的界面了

在增加question的界面中,我们需要知道是为哪个ceshi增加question,于是重写add_view方法:

class CeshiJumpQuestionAdmin(admin.ModelAdmin):
    fields = ['question']
    inlines = [CeshiJumpChoiceInline]
    list_display = ['ceshi', 'question']
    
    def add_view(self, request, form_url='', extra_context=None):
        ceshi = Ceshi.objects.get(pk=request.GET['ceshi_id'])
        return super(CeshiJumpQuestionAdmin, self).add_view(request, form_url=form_url, 
                                                            extra_context={'ceshi': ceshi})

  

这样在增加question的模板中,就多了一个ceshi的对象了

在保存question的时候,我们希望它把引用的ceshi也一起保存,重写save_model方法

class CeshiJumpQuestionAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.ceshi = Ceshi.objects.get(pk=request.POST['ceshi'])
        super(CeshiJumpQuestionAdmin, self).save_model(request, obj, form, change)

  

当然,还需要重写模板,把django的模板复制到应用的相应目录下即可。

posted on 2011-08-30 22:44  真的骄傲  阅读(471)  评论(0编辑  收藏  举报