Registration form refreshes after submitting instead of sending post request in django

Tags: , , , ,

I’m trying to register a user but the page refreshes instead of submitting the data.

At the initial stage of my project, it was working properly but when I added some more models and form it’s not working and tried to register it stopped working.

and it also doesn’t throw any errors

from django.shortcuts import render
from django.contrib.auth import authenticate,login,logout
from .models import *
from django.http import HttpResponseRedirect
from django.urls import reverse
from .form import *
from django.db import IntegrityError
from django.contrib.auth.decorators import login_required
from django.contrib import messages
# Create your views here.

def index(request):
    if not request.user.is_authenticated:
        message = f"please sign in"
    else :
        message = f"signed in as {request.user}"
    return render(request, "auctions/index.html",{
        "listings": Listings.objects.all(),
        "message": message

def login_view(request):
    if request.method == "POST":
        form = loginForm()
        email = request.POST["email"]
        password = request.POST["password"]
        user = authenticate(request,username=email,password=password)

        if user is not None:
            return HttpResponseRedirect(reverse('index'))
            return render(request, "auctions/login.html",{
                "form": form ,
                "message": "username/password not valid"
    return render(request, "auctions/login.html",{
        "form": loginForm()

def logout_view(request):
    return HttpResponseRedirect(reverse('index'))

def register(request):
    if request.POST == "POST":
        form = registerForm()
        email = request.POST["email"]

        # check passwords are same
        password = request.POST["password"]
        confirmation = request.POST["id_confirmation"]

        if password != confirmation:
            return render (request, "auctions/register.html",{
                "form": form,
                "message": "Passwords does not match"
        # Attempt to create new user
            user = myUser.objects.create_user(email,password)
        except IntegrityError:
            return render(request, "auctions/register.html", {
                "message": "Username is already taken"

        return HttpResponseRedirect(reverse('index'))

    return render(request, "auctions/register.html", {
        "form": registerForm()

def createListing(request):

    form = createListingForm(request.POST or None, request.FILES or None)

    if request.method == "POST":
        if form.is_valid():
            obj =
            obj.listed_by = request.user
            messages.success(request,"Creation successful")
        return HttpResponseRedirect(reverse('index'))

    return render(request, "auctions/create.html", {
        "form": form    

def itemPage(request,listing_id):
    return render(request, "auctions/item.html", {
        "item" : Listings.objects.get(pk= listing_id)

# still working on it
def bid(request):
    if request.method == "POST":
        new_bid = request.POST["new_bid"]

    return HttpResponseRedirect('itemPage')

from django.db import models
from django.contrib.auth.models import AbstractUser,BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

# Create your models here.
class myUserManager(BaseUserManager):
    custom user model manager where email is unique indentifiers for authenticaton
    instead of usernames.

    def create_user(self, email, password, **extra_fields):
        Create and save a User with the given email and password.
        if not email:
            raise ValueError(_('The Email must be set'))
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)

        return user

    def create_superuser(self, email, password, **extra_fields):

        Create and save a SuperUser with the given email and password.


        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff= True'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email,password, **extra_fields)

class myUser(AbstractUser):
    username = None
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'

    objects = myUserManager()

    def __str__(self):
        return f'{}'

class Listings(models.Model):
    listing_name = models.CharField(max_length=50)
    price = models.IntegerField(default=1)
    date_listed = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    item_image = models.ImageField()
    description = models.TextField(max_length=200, default="Description Not Available")
    listed_by = models.ForeignKey(myUser,on_delete=models.CASCADE, default=1,null=True)
    def __str__(self):
        return f'{self.listing_name}'

# added later not complete
class Bid(models.Model):
    item_name = models.ForeignKey(Listings,on_delete=models.CASCADE)
    bid_by_user = models.ForeignKey(myUser,on_delete=models.CASCADE)
    new_bid = models.IntegerField()

from django.forms import ModelForm
from django.db import models
from django import forms
from django.forms import Form,PasswordInput
from .models import *
from django.contrib.auth.mixins import LoginRequiredMixin

class loginForm(forms.ModelForm):

    class Meta:
        model = myUser
        fields = ['email', 'password']

        widgets = {
            # telling Django your password field in the mode is a password input on the template
            'password': forms.PasswordInput()

class registerForm(forms.ModelForm):
    confirmation = forms.CharField()

    class Meta:
        model = myUser

        fields = ['email', 'password']

        widgets = {
                # telling Django your password field in the mode is a password input on the template
                'password': forms.PasswordInput()

class createListingForm(forms.ModelForm):

    class Meta:
        model = Listings

        fields = ['listing_name', 'price', 'item_image', 'description']


{% load static %}

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

    <div class="container">
        <div class="login_form">
            <strong class="tilte">Register</strong>
            <form action="{% url 'register' %}" method="POST"> 
                {% if message %}
                    <div >
                {% endif %}
                {% csrf_token %}
                {{ form.as_p }}
                <input class="btn btn-primary" type="submit" value="Register">
                <small>If already registered click here to <a href="{% url 'login' %}">Login</a></small>

urlpatterns = [
    path('', views.index, name='index'),
    path('login/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
    path('register/', views.register, name='register'),
    path('create_listing/', views.createListing, name='create'),
    path('item/<int:listing_id>', views.itemPage, name='item'),
    path('bid/',, name='bid')

I would also like to request some other suggestions on my code. Thank you.


Well, it’s a silly mistake. I think by mistake you put request.POST inplace of request.method.

In your register view change

if request.POST == "POST": 


if request.method == "POST":

Source: stackoverflow