HttpResponseRedirect(reverse("xxx")) 出现NoReverseMatch错误

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42694291/article/details/86168195

在应用app的views.py中,用HTTPResponseRedirect重定向reverse反向解析函数的url出现如下NoReverseMatch错误:

 

from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.http import HttpResponse
import os
from app.forms import MomentForm, CommentForm
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt 

# Create your views here.

def welcome(request):
    return HttpResponse("<h1>Welcome to my site!nige sb POST提交成功!</h1>")

@csrf_exempt   #暂时屏蔽csrf
def moments_input(request):
    if request.method == 'POST':
        form = MomentForm(request.POST)
        if form.is_valid():
            print("posting!")
            moment = form.save()
            moment.save()
            return HttpResponseRedirect(reverse("app.views.welcome"))
            # return HttpResponse("<h1>Welcome to my site!nige sb POST提交成功!</h1>")

    else:
        form = MomentForm()

    PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    return render(request, os.path.join(PROJECT_ROOT, 'app/templates', 'moments_input.html'), {'form':form})

当表单提交时,会出现如下错误:

原因是因为reverse的使用方法的错误,下面是reverse的函数定义:

reverse(viewnameurlconf=Noneargs=Nonekwargs=Nonecurrent_app=None)

viewname为views.py中视图函数名即可,无需加""号,我的解决方法就是将reverse("app.views.welcome")改成reverse(welcome)即可

 

展开阅读全文

没有更多推荐了,返回首页