为了账号安全,请及时绑定邮箱和手机立即绑定

每次刷新 http://127.0.0.1:8000/blog/edit/action/ 都会创建一篇文章,有人遇到这个问题吗

每次刷新这个界面,都会创建一篇文章,有人遇到这个问题吗

正在回答

5 回答

改成这样就行了,亲测有效

def edit_action(request):
    title=request.POST.get('title','TITLE')
    content=request.POST.get('content','CONTENT')
    models.Article.objects.create(title=title,content=content)
    response = redirect('/blog/index')
    return response


0 回复 有任何疑惑可以回复我~

同问!

0 回复 有任何疑惑可以回复我~

我也遇到了,明明页面上展示的是主页的内容,url却是action的,很奇怪啊

0 回复 有任何疑惑可以回复我~

我用的python3.73

各种测试用了好几个小时,终于成功做出了视频中的几个跳转的功能,文件分享给大家:

index.html

<body>
<h1>
    <a href="{% url 'edit_page' %}">新文章</a>
</h1>
{% for article in articles %}
    <h3>
    <a href="/blog/article/{{ article.id }}">{{ article.title }}</a>
    </h3>
{% endfor %}
</body>

edit_page.html:

<body>
<form action="{% url 'edit_action' %}" method="post">
    {% csrf_token %}
    <label>
        <input type="text" name="title"/>
    </label>
    <br>
    <label>
        <input type="text" name="content"/>
    </label>
    <br>
    <input type="submit" value="提交">
</form>
</body>

urls.py:

urlpatterns = [
    path(r'', views.index),
    path('article/<int:article_id>', views.article_page),
    path('edit/', views.edit_page, name='edit_page'),
    path('edit/action', views.edit_action, name='edit_action'),

views.py:

def index(request):
    # article = models.Article.objects.get(pk=1)
    articles = models.Article.objects.all()
    return render(request, 'blog/index.html', {'articles': articles})

def article_page(request,article_id):
    article = models.Article.objects.get(pk=article_id)
    return render(request,'blog/article_page.html',{'article':article})

def edit_page(request):
    return render(request,'blog/edit_page.html')

def edit_action(request):
    title = request.POST.get('title', 'TITLE')
    content = request.POST.get('content', 'CONTENT')
    models.Article.objects.create(title=title, content=content)
    articles = models.Article.objects.all()
    return render(request, 'blog/index.html', {'articles': articles})


真是不容易啊,前期的课程听起来很顺,到后边各种不致就都出来了!

2 回复 有任何疑惑可以回复我~

因为这个url对应views里的动作是在数据库里创建一篇文章

1 回复 有任何疑惑可以回复我~
#1

慕运维6045466

那有没有什么办法在跳回去以后把url修改掉
2019-08-17 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
django入门与实践
  • 参与学习       65201    人
  • 解答问题       868    个

手把手带你进入Django开发的大门,充分领略Django的魅力

进入课程

每次刷新 http://127.0.0.1:8000/blog/edit/action/ 都会创建一篇文章,有人遇到这个问题吗

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信