2011-11-09 72 views
4

標準的例子:Django的 - 管理:編輯子模型沒有inlineForm

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

class Book(models.Model): 
    title = models.CharField(max_length=100) 
    author = models.ForeignKey(Author) 
    #... Many other fields ... 

我想從Author改變頁面編輯Book秒。
我試過InlineModelAdmin,但由於Book有很多字段,所以編輯並不容易。
這就是爲什麼我試圖把作者/更改模板上的兒童的鏈接。

<ul> 
    <li><a href="{% url admin:content_scribpart_add %}">Add a Book</a></li> 
{% for book in original.book_set.all %} 
    <li><a href="{% url admin:myapp_book_change book.id %}">Edit {{ book }}</a></li> 
{% endfor %} 
</ul> 

但是有幾個問題

  • 我如何預填充相關Author ID在Book形式
  • 我怎樣才能讓保存按鈕返回到相關Author
  • 我在正確的軌道上嗎?

回答

4

是的,當然。

  1. 追加author主鍵GET參數,您的網址:

    <ul> 
        <li><a href="{% url admin:content_scribpart_add %}?author={{ object_id }}">Add a Book</a></li> 
    {% for book in original.book_set.all %} 
        <li><a href="{% url admin:myapp_book_change book.id %}?author={{ object_id }}">Edit {{ book }}</a></li> 
    {% endfor %} 
    </ul> 
    
  2. 修改書相應ModealAdmin,覆蓋response_add() and response_change()。請注意,我們也override formfield_for_forein_key以預填充author場:

    from django.http import HttpResponseRedirect 
    from django.core.urlresolvers import reverse 
    
    class BookAdmin(admin.ModelAdmin): 
    
        def formfield_for_foreignkey(self, db_field, request, **kwargs): 
         if db_field.name == "author":      
          try: 
           author_pk = int(request.GET.get('author', ''),) 
          except ValueError:   
           pass 
          else: 
           kwargs["initial"] = Author.objects.get(pk=author_pk) 
    
         return super(BookAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) 
    
        def response_add(self, request, obj, post_url_continue=None): 
         return HttpResponseRedirect(reverse('admin:myapp_author_change', args=(obj.author.pk,)) 
         ) 
    
        def response_change(self, request, obj, post_url_continue=None): 
         return HttpResponseRedirect(reverse('admin:myapp_author_change', args=(obj.author.pk,)) 
         ) 
    
+0

'Author.objects.filter(PK = author_pk)'過濾器選擇框,但不預填充 –

+0

最後我將使用'kwargs [「initial」] = Author.objects.get(pk = author_pk)'而不是'kwargs [「queryset」] = Author.objects.filter(pk = author_pk)' –

+0

它也是'admin:myapp_author_change '而不是'admin_myapp_author_change' –