Это проблема, с которой я долго боролся, поэтому размещу ее здесь в надежде получить какое-то руководство.
Когда я создаю новый дочерний экземпляр элемента, я пытаюсь передать значение pk от родителя, поэтому дочерний экземпляр создается под правильным родителем.
Parent Models.py
class listofbooks(models.Model):
booktitle = models.CharField(max_length = 100)
description = models.TextField(null=True)
Child Models.py
class author(models.Model):
listofbooks = models.ForeignKey("books.listofbooks",on_delete=models.CASCADE, blank=True, null=True)
authorname= models.CharField(max_length = 100, null=True)
authorage = models.IntegerField()
Parent urls.py
app_name = 'books'
urlpatterns = [
path('', BookListView.as_view(), name='book-list-view'),
path('new/', BookCreateView.as_view(), name='book-create'),
path('<int:listofbooks_pk>/', BookDetailView.as_view(), name='book-detail'),
]
Child urls.py
app_name = 'author'
urlpatterns = [
path('<int:listofbooks_pk>/authors', AuthorListView.as_view(), name='author-list'),
path('<int:author_pk>', AuthorInfoView.as_view(), name='author-detail'),
path('<int:listofbooks_pk>/new/', AuthorCreateView.as_view(), name='author-create'),
]
Child views.py
class AuthorInfoView(DetailView):
model = author
pk_url_kwarg = "author_pk"
class AuthorListView(ListView):
model = author
pk_url_kwarg = "author_pk"
context_object_name = 'listofauthors'
def get_queryset(self, *args, **kwargs):
return author.objects.filter(listofbooks=self.kwargs['listofbooks_pk'])
class AuthorCreateView(CreateView):
model = author
pk_url_kwarg = "listofbooks_pk"
fields = ['authorname','authorage']
def get_success_url(self, *args, **kwargs):
return reverse('author:author-detail',kwargs={'author_pk':self.object.pk})
Вот список author_list. html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>This is the list of Authors page</h1>
{% for item in listofauthors %} <br>
{{ item.authorname }} <br>
{{ item.authorage }} <br>
<a href = "{% url 'author:author-detail' item.id %}">View Author Detail</a> <br>
{% endfor %}
<a href = "{% url 'author:author-create' object.id %}" >Add Author</a> <br>
</body>
</html>
Сообщение об ошибке
NoReverseMatch at /author/1/authors
Reverse for 'author-create' with arguments '('',)' not found. 1 pattern(s) tried: ['author/(?P<listofbooks_pk>[0-9]+)/new/$']
Request Method: GET
Request URL: http://192.168.1.70:8080/author/1/authors
Django Version: 3.0.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'author-create' with arguments '('',)' not found. 1 pattern(s) tried: ['author/(?P<listofbooks_pk>[0-9]+)/new/$']
Exception Location: /home/pi/test/venv/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677
Python Executable: /home/pi/test/venv/bin/python
Python Version: 3.7.3
Python Path:
['/home/pi/test/booklist',
'/home/pi/test/venv/lib/python37.zip',
'/home/pi/test/venv/lib/python3.7',
'/home/pi/test/venv/lib/python3.7/lib-dynload',
'/usr/lib/python3.7',
'/home/pi/test/venv/lib/python3.7/site-packages']
Server time: Sun, 16 Feb 2020 19:56:08 +0000
Если Я заменяю эту строку в author_list. html и добавляю число там, оно работает нормально. Поэтому замените
<a href = "{% url 'author:author-create' object.id %}" >Add Author</a> <br>
на
<a href = "{% url 'author:author-create' 1 %}" >Add Author</a> <br>
Насколько я понимаю, мне нужно получить значение listofbooks.pk, где находится object.id, но теперь я нахожусь в тупике как как решить это.