反转 'edit' 没有找到任何参数。尝试了 1 个模式:['articles/edit/(?P<pk>[0-9]+)/$']

Ane*_*han 3 django django-forms python-3.x

我是 Django 的初学者,现在我正在开发一个博客应用程序。在文章编辑部分,我被卡住了,我不知道为什么会显示此错误。搜索了很多,找不到答案

NoReverseMatch at /articles/edit/2/

Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['articles/edit/(?P<pk>[0-9]+)/$']
Run Code Online (Sandbox Code Playgroud)

edit_articles 部分在

视图.py

@login_required(login_url="/accounts/login/")
def edit_articles(request, pk):
    article = get_object_or_404(Article, id=pk)
    if request.method == 'POST':
        form = forms.CreateArticle(request.POST, instance=article)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('articles:myarticles')
    else:
        form = forms.CreateArticle(instance=article)
    return render(request, 'articles/article_edit.html', {'form': form})
Run Code Online (Sandbox Code Playgroud)

article_edit.html

NoReverseMatch at /articles/edit/2/

Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['articles/edit/(?P<pk>[0-9]+)/$']
Run Code Online (Sandbox Code Playgroud)

网址.py

from django.urls import path
from . import views

app_name = 'articles'

urlpatterns = [
    path('', views.article_list, name='list'),
    path('create/', views.article_create, name='create'),
    path('edit/<int:pk>/', views.edit_articles, name='edit'),
    path('myarticles/',views.my_articles, name='myarticles'),
    path('<slug>/', views.article_detail, name='details'),
]
Run Code Online (Sandbox Code Playgroud)

my_articles.html

第四个按钮是用主键触发编辑功能并重定向到编辑页面

<tbody>
{% if articles %}
{% for article in articles %}
<tr class="table-active">
  <th scope="row">1</th>
  <td>{{ article.title }}</td>
  <td>{{ article.date }}</td>
  <td><a href="{% url 'articles:edit' pk=article.pk %}"><button type="button" class="btn btn-info">Edit</button></a></td>
{% endfor %}
</tr>
{% else %}
<tr>
  <td colspan=4 class="text-center text-danger">Oops!! You dont have any articles.</td>
</tr>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

小智 9

在您的模板 article_edit.html - 发布 url 需要一个 pk,您需要传递一个 pk,就像您为模板 my_articles.html 所做的一样

<div class="create-article"><form class="site-form" action="{% url 'articles:edit' pk=form.instance.pk %}" method="post" enctype="multipart/form-data">{% csrf_token %}...
Run Code Online (Sandbox Code Playgroud)

这样 django 就知道你正在编辑哪篇文章