2016-04-30 11 views
1

Ich lerne Django und versuche ein Formular zu erstellen, mit dem ich die Informationen eines Teilnehmers an die Datenbank senden kann.Django Redirect zur Indexansicht mit korrekter URL nach der Formularübergabe

Ich habe eine Indexansicht, die alle Teilnehmerliste:

http://127.0.0.1:8000/participants/

einen Knopf auf dem Index klicken, wird gehen Vorlage zu bilden:

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

Nach Absenden des Formulars , die Seite kehrt zurück zur Indexansicht, aber die URL ist nicht korrekt, sie bleibt bei http://127.0.0.1:8000/participants/add_participant/

stecken

Wenn ich den Browser sofort aktualisiere, fügt er der Datenbank einen weiteren Datensatz hinzu.

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'), 
] 

ich versuchte, die

return index(request) 
Schalt

zu:

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

Sie löst das Problem ... aber ich bezweifle, dass dies der „richtige“ Weg, es zu tun. Wie kann dieses Problem behoben werden?

Antwort

4

Sie können nur den Pfad zu der Umleitungsantwort passieren:

return HttpResponseRedirect("/participants/") 

diese Weise, wenn Sie Ihre Domain ändern, wird die Umleitung arbeiten.

eine andere Lösung ist reverse

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

Das funktionierte zu verwenden. Vielen Dank! – WonderSteve

Verwandte Themen