Adithya
Adithya

Reputation: 1857

Redirect to home page with arguments after submiting form in django

I am trying to add details of students,which is submitted using django & 'POST' method. On submission I save the details in my 'py' file. After that I want to redirect to home page. Earlier I used

return render_to_response("home.html",{ "edit":0,"msg":'saved'}, context_instance=RequestContext(request))

But on each refreshing of the home page it will insert data to table. Then I tried to used "HttpResponseRedirect" , but it will not support argument passing. How can I resolve this ?

add.py

stud = student(name=request.POST['studname'])
stud.save()
return render_to_response("home.html",{ "edit":0,"msg":'saved'}, context_instance=RequestContext(request))

student.html

<form id = "addForm" name = "addForm" action = "" method = 'POST' >
<table>
 <tr>
   <td>Name.</td>
   <td><input type="text" name="studname" id="studname"></td> 
 </tr>
</table>
</form>

Upvotes: 1

Views: 1441

Answers (2)

Nagaraj Tantri
Nagaraj Tantri

Reputation: 5262

You should look into Post/Redirect/Get.

Basically,

  1. Ensure, you have a POST method that handles the post
  2. Then REDIRECT the user to a specific page.
  3. Which then has a GET request to serve the page.

Here is what you can think:

Use Django's redirect

def submitting_student(request):
   if request.method == "POST":
        stud = student(name=request.POST['studname'])
        stud.save()
        return redirect("home.html", { "edit":0, "msg":'saved' })

   return render_to_response("student.html")

Here is another post on the same topic of PRG pattern

Upvotes: 5

PhoebeB
PhoebeB

Reputation: 8570

Try checking if the request is a post first in add.py

eg.

msg = ""

   if request.method == "POST":
        stud = student(name=request.POST['studname'])
        stud.save()

        msg = "saved"

   return render_to_response("home.html",{ "edit":0,"msg":msg}, context_instance=RequestContext(request))

Upvotes: 0

Related Questions