首页 > 解决方案 > 在 Django 中,创建新子实例时我无法通过 url 传递 pk 值

问题描述

这是我一直在努力解决的一个问题,所以在这里发布它希望得到一些指导。

当我创建一个项目的新子实例时,我很难从父项传递 pk 值,因此子实例是在正确的父项下创建的。

父模型.py

class listofbooks(models.Model):
    booktitle = models.CharField(max_length = 100)
    description = models.TextField(null=True) 

子模型.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()

父 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'),
]

子 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'),
]

子视图.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 所在的位置,但现在对于如何解决这个问题处于死胡同。

标签: djangopython-3.x

解决方案


推荐阅读