Python 与#x27相反;编辑帖子';带参数';(';';,)';没有找到。尝试了1个模式:[';编辑#post/(?P<;post#id>;\\d+;)/$&&x27;]

Python 与#x27相反;编辑帖子';带参数';(';';,)';没有找到。尝试了1个模式:[';编辑#post/(?P<;post#id>;\\d+;)/$&&x27;],python,django,Python,Django,我正在学习Django教程,在尝试在我的博客应用程序中编辑帖子时出现此错误。我使用Django版本:2.0.6和Python版本:3.6.5 models.py from django.db import models class BlogPost(models.Model): title = models.CharField(max_length=100) text = models.TextField() def __str__(self): re

我正在学习Django教程,在尝试在我的博客应用程序中编辑帖子时出现此错误。我使用Django版本:2.0.6和Python版本:3.6.5

models.py

from django.db import models

class BlogPost(models.Model):
    title = models.CharField(max_length=100)
    text = models.TextField()

    def __str__(self):
        return self.title
url.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^new_post/', views.new_post, name='new_post'),
    url(r'^edit_post/(?P<post_id>\d+)/$', views.edit_post, name='edit_post'),
]
forms.py

from django import forms
from .models import BlogPost

class BlogForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['title', 'text']
问题

当我点击索引页面上的编辑文章链接时,我得到了前面提到的错误。使用这种方法创建一篇新文章是完美的,但编辑却不能。 我被这个问题缠住了,不知道出了什么问题

我尝试过的

  • 我尝试用django.url.path和相应的模式替换django.conf.url.url
  • 我已将链接更改为按钮
  • 我试过了
  • 我已经阅读了StackOverflow和尽可能多的主题

  • 感谢您的帮助。提前谢谢你

    在您的
    博客/edit_post.html
    中使用
    post.id

    <form action="{% url 'edit_post' post.id %}" method='post'>
        ...
    </form>
    
    def edit_post(request, post_id):
        post = BlogPost.objects.get(id=post_id)
        text = post.text
        title = post.title
        if request.method != 'POST':
            form = BlogForm(instance=post)
        else:
            form = BlogForm(instance=post, data=request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('index'))
        context = {'title': title, 'text': text, 'form': form}
        return render(request, 'blog/edit_post.html', context)
    
    from django import forms
    from .models import BlogPost
    
    class BlogForm(forms.ModelForm):
        class Meta:
            model = BlogPost
            fields = ['title', 'text']
    
    <form action="{% url 'edit_post' post.id %}" method='post'>
        ...
    </form>
    
    def edit_post(request, post_id):
        post = BlogPost.objects.get(id=post_id)
        ...
    
        context = {
                  'title': title, 
                  'text': text, 
                  'form': form,
                  'post': post # here
                  }
        return render(request, 'blog/edit_post.html', context)