I am trying to create an ecommerce application. When a user tries to create a listing, the listing is not saved. ‘Save’ method does not work.
Model:
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.contrib.auth.decorators import login_required
from django.utils import timezone
class User(AbstractUser):
pass
class Listings(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=64)
description = models.CharField(max_length=300)
startBids = models.DecimalField(max_digits=5, decimal_places=2)
seller = models.ForeignKey(User,on_delete=models.CASCADE,default=None)
category = models.CharField (max_length=64,default=None)
img = models.CharField(
max_length=200, default=None, blank=True, null=True)
created_at = models.DateTimeField(default=None)
def __str__(self):
return f"{self.id}: {self.title} {self.startBids} {self.seller}"
form.py
from django import forms
class CreateListingForm(forms.Form):
title = forms.CharField(max_length=64)
description = forms.CharField(max_length=300)
startBids = forms.DecimalField(max_digits=5, decimal_places=2)
img = forms.CharField(max_length=200, default=None, blank=True, null=True)
Views.py
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django import forms
from auctions.forms import CreateListingForm
from django.utils import timezone
from datetime import datetime, timedelta, tzinfo
from .models import *
@login_required(login_url='/login')
def CreateListing(request):
if request.method == "POST":
listing = Listings()
listing.title = request.POST["title"]
listing.description = request.POST["description"]
listing.startBids = request.POST["startBids"]
listing.seller = request.user.username
listing.created_at = datetime.now()
listing.save()
return HttpResponseRedirect(reverse("index",))
else:
NewListing = CreateListingForm()
return render(request, "auctions/createListing.html",{
"NewListing": NewListing
})