我在我的繩索盡頭弄清楚爲什麼一個簡單的表單重定向不起作用。我通過POST請求提交了一個帶有一個文本字段的表單,該表單與相同views.py文件中某個函數的某些數據組合在一起,然後將其保存到數據庫的模型中。出於某種原因,通過我在提交表單時設置的重定向方案,我得到了表單的第二個副本。Django - 表單提交沒有重定向
feedbackapp/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from .forms import FeedbackForm
from .models import Feedback
def record_feedback(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
feedback = Feedback()
feedback.submitter_ip = get_client_ip(request)
feedback.feedback_text = form.cleaned_data['feedback']
feedback.save()
return HttpResponseRedirect(reverse('feedbackapp:thanks'))
elif request.method == 'GET':
form = FeedbackForm()
return render(request, 'feedbackapp/feedback_form.html', {'form': form})
def thanks(request):
return render(template_name='feedbackapp/thanks.html',request=request)
# https://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1] # needs to be the last element in array for Heroku
else:
ip = request.META.get('REMOTE_ADDR')
return ip
feedbackapp/forms.py
from django import forms
class FeedbackForm(forms.Form):
feedback = forms.CharField(label='Feedback', max_length=5000)
feedbackapp/templates/feedbackapp/feedback_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Anonymous Feedback</title>
</head>
<body>
<form action="/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit"/>
</form>
<p><i>Note: IP addresses are collected with each submission.</i></p>
</body>
</html>
feedbackapp/templates/feedbackapp/thanks.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Thanks!</title>
</head>
<body>
<p>Thanks for your feedback.</p>
</body>
</html>
feedbackapp/urls.py
from django.conf.urls import url
from .views import record_feedback, thanks
urlpatterns = [
url('', record_feedback, name='feedback'),
url('thanks/', thanks, name='thanks'),
]
anonfeed/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('feedbackapp.urls'), namespace='feedbackapp'),
]
這幾乎是如果thanks
觀點不符合URL和模板關聯。
交換你的'feedbackapp.urls.urlpatterns'的順序,或者把'$'的'feedback'模式,以表明它僅應如果後面什麼也沒有,那麼去那裏,否則無論你去哪個網址,它都會進入你的「反饋」視圖。 – Jorden