我是Django的新手,正在尝试建立一个简单的联系表单,该表单将在成功提交后重定向到感谢页面。提交后,我无法使其重定向到感谢页面,并遇到以下错误:
NoReverseMatch at /contact/
Reverse for 'thanks' not found. 'thanks' is not a valid view function or pattern name.
这是我的urls.py
app_name = 'home'
urlpatterns = [
url(r'^$', views.HomePageView.as_view()),
url(r'^contact/$', views.ContactView, name='contact'),
url(r'^thanks/$', views.ThanksView, name='thanks'),
]
和我的views.py
def ContactView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin@example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
return render(request, 'contact.html', {'form': form})
def ThanksView(request):
return render(request, 'thanks.html', {})
我在settings.py
TEMPLATES = [
{
'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, '/home', 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# Third Party Apps
'social_django.context_processors.backends', # <--
'social_django.context_processors.login_redirect', # <--
],
},
},
]
有人可以指出我在哪里犯错吗?
谢谢!
答案 0 :(得分:4)
这应该有效
return redirect('home:thanks')
答案 1 :(得分:0)
希望有帮助:
return redirect(reverse('appname:urlname'))
或者使用 kwargs,如果是“urlname/”:
return redirect(reverse('appname:urlname', kwargs={'kwarg':value}))
答案 2 :(得分:0)
如果你定义 app_name 为 app 的名字 您应该像这样为您的视图编写网址
<a href='{% url "name_of_app:name_of_view" %}'> Link </a>