Django - Admin: editing a child model without a built-in template

Standard example:

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

I would like to edit the Book on the Author change page.
I tried with InlineModelAdmin , but since the Book has many fields, it is not easy to edit.
That is why I tried to establish links to children on the author / change template.

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

But there are a few questions

  • How can I pre-create the associated Author identifier in the Book form
  • How to make the "Save" button return to the associated Author
  • Am I on the right track?
+4
source share
1 answer

Oh sure.

  • Add author primary key as a GET parameter to your URL:

     <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> 
  • Change the appropriate ModealAdmin for the workbook, override response_add() and response_change() . Note that we also override formfield_for_forein_key to pre-populate the author field:

     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,)) ) 
+4
source

Source: https://habr.com/ru/post/1380372/


All Articles