Wei Xu
Wei Xu

Reputation: 1659

Why does my Django request.method is 'GET' not 'POST'?

I met this strange problem when doing a pre-populated form. In my template, the form method is clearly stated as POST:

<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">{% csrf_token %}

But in my view function, the request.method turns out to be GET.

Below is my view function:

def editProfile(request,template_name):
    theprofile = request.user.profile

    print theprofile.fullname

    notificationMSG = ''
    print request.method

    if request.method == 'POST':
        form = UserProfileForm(request.POST,request.FILES, instance=theprofile)
        if form.is_valid():
            form.save()
            notificationMSG = "success!"

    else:
        form = UserProfileForm()
        print "error"

    dic = {'form':form,
           'notificationMSG':notificationMSG}

    return render_to_response(template_name, dic, context_instance=RequestContext(request))

When I run it, it prints out GET. Anyone met this odd before?

Upvotes: 4

Views: 4810

Answers (5)

Sumit Kumar
Sumit Kumar

Reputation: 1

I am also facing this problem but, In my case, in input type, I have written type =" button" when I change it to type="submit" it get resolved.

Sorry, I get misunderstood when again I face the same problem then I got actual solution.

Upvotes: -1

Myzel394
Myzel394

Reputation: 1317

Here are the steps I needed so far to solve this kind of error:

  1. Add method="post" to your <form> element
  2. Add a missing "/" at the end of the url at the action property on your <form> element
  3. Add a type="submit" to your <button> element

Ps. Don't forget to add {% csrf_token %} after your <form>.

Upvotes: 1

py_ios_dev
py_ios_dev

Reputation: 497

In my case I was missing a "/" at the end of action in the HTML Template, while posting.

Upvotes: 6

Stephen
Stephen

Reputation: 1148

Every time I submitted my form with action="" I was getting a GET response, but once I filled the actual URL action="/client/" it went through as a POST.

Upvotes: 1

Santosh Ghimire
Santosh Ghimire

Reputation: 3145

When you are loading the form and retrieving remote data by hitting a url, the request method is GET. When you fill the form values and submit the form(with post method) i.e. insert/update remote data, the request method is POST.

So, in your code when you print request.method, the output is GET when you are loading the form. This has nothing to do with your pre-populated form.

Upvotes: 3

Related Questions