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
views.py
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: login(request,user) return HttpResponseRedirect(reverse('index')) else: 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): logout(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 try: user = myUser.objects.create_user(email,password) user.save() except IntegrityError: return render(request, "auctions/register.html", { "form":form, "message": "Username is already taken" }) login(request,user) return HttpResponseRedirect(reverse('index')) return render(request, "auctions/register.html", { "form": registerForm() }) @login_required(login_url='login') def createListing(request): form = createListingForm(request.POST or None, request.FILES or None) if request.method == "POST": if form.is_valid(): obj = form.save(commit=False) obj.listed_by = request.user obj.save() 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 @login_required(login_url='login') def bid(request): if request.method == "POST": new_bid = request.POST["new_bid"] return HttpResponseRedirect('itemPage')
models.py
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) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) 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' REQUIRED_FIELDS = [] objects = myUserManager() def __str__(self): return f'{self.email}' 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()
forms.py
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']
register.html
{% load static %} <!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>Login</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="login_form"> <strong class="tilte">Register</strong> <form action="{% url 'register' %}" method="POST"> {% if message %} <div > {{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> </form> </div> </div> </body> </html>
urls.py
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/', views.bid, name='bid') ]
I would also like to request some other suggestions on my code. Thank you.
Advertisement
Answer
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":
to
if request.method == "POST":