Page not found (404) Request Method: POST

Viewed 144

I've been stuck with this error for a few days and am not able to find where the mistake is.

views section

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

# Create your views here.

def register(request):
    if(request.method=='POST'):
        username=request.POST['username']
        password1=request.POST['password1']
        password2=request.POST['password2']
        user=User.objects.create_user(username=username,password=password1)
        user.save();
        print("user created")
        return redirect('/')
    else:
        return render(request,'registration.html')

urls.py section

from django.urls import path
from . import views
urlpatterns=[path('register/',views.register,name="register")]

html section

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration</title>
</head>
<body>
    <form action="register" method="POST">
        {% csrf_token %}
        USERNAME  <input type="text" name="username" id=""> <br><br>
        PASSWORD  <input type="password" name="password1" id=""> <br><br>
        RETYPE PASSWORD  <input type="password" name="password2" id=""> <br><br>
        <input type="submit" value="">    
    </form>
</body>
</html>
1 Answers

Issue

  1. create_user() doesn't require save() method to be called for creating instance.

  2. You have given only action="register" which is not valid at all, you need to give url tag, to perfectly make route. That's the case for page not found which is the main question.

So, with some modifications try below code:

Views.py

def register(request):
    if(request.method=='POST'):
        username=request.POST['username']
        password1=request.POST['password1']
        password2=request.POST['password2']
        user=User.objects.create_user(username=username,password=password1)
        print("user created")
        return redirect('/')
    else:
        return render(request,'registration.html')

Template file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration</title>
</head>
<body>
    <form action="{% url 'register' %}" method="POST">
        {% csrf_token %}
        USERNAME  <input type="text" name="username" id=""> <br><br>
        PASSWORD  <input type="password" name="password1" id=""> <br><br>
        RETYPE PASSWORD  <input type="password" name="password2" id=""> <br><br>
        <input type="submit" value="Save">    
    </form>
</body>
</html>
Related