Vansh_Chaudhary
Vansh_Chaudhary

Reputation: 81

Requesting for POST method but only GET is working

The Form in register.html request for POST method but GET method is working. Submit is calling register method in views.py using GET method, but this shouldn't be happening.

Error :

Request Method: POST
Request URL: http://127.0.0.1:8000/Profile/register/register/

views.py

from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.contrib.auth.models import User
from django.contrib import messages

def register(request):
    if request.method == 'POST':
        return redirect('/')
    else:
        return render(request, 'register.html')

register.html

<form action="register" method="post">
    {% csrf_token %}
    <input type="Submit">
</form>

urls.py of Project

from re import template
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
    path('Profile/', include('Profile.urls')),

    path('accounts/', include('django.contrib.auth.urls')),

    path('login/', auth_views.LoginView.as_view(template_name="login.html"),
    name='login'),
    path('logout/', auth_views.LogoutView.as_view(),
    name='logout'),
    path('reset_password/', auth_views.PasswordResetView.as_view(), 
    name = 'reset_password'),
    path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(),
    name='password_reset_done'),
    path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(),
    name='password_reset_confirm'),
    path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(),
    name='password_reset_complete')
]

urls.py of Profile app

from django.urls import path
from Profile import views

urlpatterns = [
    path('profile/', views.profile, name='profile'),
    path('register/', views.register, name='register'),
]

Upvotes: 2

Views: 689

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

The URL is register/. Because you do not use a trailing slash, Django will make a redirect with a slash, but that will thus result in a GET request, not a POST request.

You thus should work with:

<form action="/profile/register/" method="post">
    {% csrf_token %}
    <input type="Submit">
</form>

or better is to work with the {% url … %} template tag [Django-doc]:

<form action="{% url 'register' %}" method="post">
    {% csrf_token %}
    <input type="Submit">
</form>

Upvotes: 1

Related Questions