2016-04-30 9 views
1

私はDjangoを学習しており、参加者の情報をデータベースに送信できるフォームを作成しようとしています。フォームを送信した後Djangoはフォーム提出後に正しいURLでインデックスビューにリダイレクトします

http://127.0.0.1:8000/participants/add_participant/

:提出を形成するために行くのインデックスのボタンをクリックする

http://127.0.0.1:8000/participants/

私はすべての参加者をリストする、インデックス・ビューを持っていますページはインデックスビューに戻りますが、URLが正しくない場合は、http://127.0.0.1:8000/participants/add_participant/

ブラウザを直ちに更新すると、データベースに別のレコードが追加されます。

add_participant.html

<!DOCTYPE html> 
<html> 
    <head> 
     <title>This is the title</title> 
    </head> 

    <body> 
     <h1>Add a Participant</h1> 

     <form id="participant_form" method="post" action="/participants/add_participant/"> 

      {% csrf_token %} 
      {{ form.as_p }} 

      <input type="submit" name="submit" value="Create Participant" /> 
     </form> 
    </body> 

</html> 

views.py

from django.shortcuts import render, get_object_or_404, redirect 
from django.http import HttpResponse, HttpResponseRedirect 

from participants.models import Participant 
from .forms import ParticipantForm 


# Create your views here. 
def index(request): 
    participant_list = Participant.objects.order_by('-first_name')[:50] 
    context = {'participants': participant_list} 
    return render(request, 'participants/index.html', context) 

def add_participant(request): 
    if request.method == 'POST': 
     form = ParticipantForm(request.POST) 
     if form.is_valid(): 
      form.save(commit=True) 
      return index(request) 
    else: 
     form = ParticipantForm() 


     return render(request, 'participants/add_participant.html', {'form': form}) 

urls.py

from django.conf.urls import url 

from . import views 
from .models import Participant 

app_name = 'participants' 

urlpatterns = [ 
    url(r'^$', views.index, name='index'), 
    url(r'add_participant/$', views.add_participant, name='add_participant'), 
] 

Iは

return index(request) 
を切り替える試み

return HttpResponseRedirect("http://127.0.0.1:8000/participants/") 

それは問題を解決します...しかし、私は、これはそれを行うには「正しい」方法である疑い。この問題を解決する正しい方法は何ですか?

答えて

4

あなたはリダイレクト応答にだけパスを渡すことができます:

return HttpResponseRedirect("/participants/") 

あなたのドメインを変更した場合、この方法で、リダイレクトが動作します。

他のソリューションを働いたreverse

from django.core.urlresolvers import reverse 
# ... 
return HttpResponseRedirect(reverse(index)) 
+0

を使用することです。ありがとう! – WonderSteve

関連する問題