When I am running runserver command and the server starts and entering to the admin pannel there is an OperationalError
In models.py:
# from email.policy import default
# from pyexpat import model
from django.db import models
# from unicodedata import decimal
from shortuuid.django_fields import ShortUUIDField
from django.utils.html import mark_safe
from userauths.models import CustomUser
STATUS_CHOICE=(
("process","Processing"),
("shipped","Shipped"),
("delevered","Delevered"),
)
STATUS=(
("draft","Draft"),
("disable","Disable"),
("rejected","Rejected"),
("In_review","In Review"),
("published","Published"),
)
RATING=(
(1,"⭐☆☆☆☆"),
(2,"⭐⭐☆☆☆"),
(3,"⭐⭐⭐☆☆"),
(4,"⭐⭐⭐⭐☆"),
(5,"⭐⭐⭐⭐⭐"),
)
# Create your models here.
def user_directory_path(instance,filename):
return 'user_{0}/{1}'.format(instance.user.id, filename)
class Category(models.Model):
cid=ShortUUIDField(length=10,max_length=100,prefix="cat",alphabet="abcdef")
title=models.CharField(max_length=100,default="Food")
image=models.ImageField(upload_to="category",default="category.jpg")
class Meta:
verbose_name_plural="Categories"
def catagory_image(self):
return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url))
def __str__(self):
return self.title
class Tags(models.Model):
pass
class Vendor(models.Model):
vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef")
title=models.CharField(max_length=100,default="Nest")
image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg")
description=models.TextField(null=True, blank=True,default="Normal Vendorco")
address=models.CharField(max_length=100, default="6,Dum Dum Road")
contact=models.CharField(max_length=100, default="+91")
chat_resp_time=models.CharField(max_length=100,default="100")
shipping_on_time=models.CharField(max_length=100,default="100")
authenticate_rating=models.CharField(max_length=100,default="100")
days_return=models.CharField(max_length=100,default="100")
warranty_period=models.CharField(max_length=100,default="100")
user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
class Meta:
verbose_name_plural="Vendors"
def Vendor_image(self):
return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url))
def __str__(self):
return self.title
class Product(models.Model):
pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef")
user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True)
title=models.CharField(max_length=100,default="Apple")
image=models.ImageField(upload_to=user_directory_path,default="product.jpg")
description=models.TextField(null=True, blank=True,default="This is a product")
price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99)
old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99)
specifications=models.TextField(null=True, blank=True)
tags=models.ForeignKey(Tags, on_delete=models.SET_NULL ,null=True)
product_status=models.CharField(choices=STATUS, max_length=10,default="In_review")
status=models.BooleanField(default=True)
in_stock=models.BooleanField(default=True)
featured=models.BooleanField(default=False)
digital=models.BooleanField(default=False)
sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef")
date=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(null=True,blank=True)
class Meta:
verbose_name_plural="Products"
def product_image(self):
return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url))
def __str__(self):
return self.title
def get_percentage(self):
new_price=(self.price/self.old_price) * 100
return new_price
class ProductImages(models.Model):
images=models.ImageField(upload_to="product-image",default="product.jpg")
product=models.ForeignKey(Product, on_delete=models.SET_NULL ,null=True)
date=models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural="Product Images"
######################################################Care,Order,CartItemsand Address###########################
class CartOrder(models.Model):
user=models.ForeignKey(CustomUser,on_delete=models.CASCADE)
price= models.DecimalField(max_digits=10, decimal_places=2,default="1.99")
paid_status=models.BooleanField(default=False)
order_date=models.DateTimeField(auto_now_add=True)
product_status=models.CharField(choices=STATUS_CHOICE, max_length=30,default="prodcessing")
class Meta:
verbose_name_plural="Cart Order"
class CartOrderItems(models.Model):
order=models.ForeignKey(CartOrder,on_delete=models.CASCADE)
invoice_num = models.BigIntegerField(blank=True,null=True)
product_status=models.CharField(max_length=200)
item=models.CharField(max_length=100)
image=models.CharField(max_length=100)
qty=models.BigIntegerField(default=0)
price= models.DecimalField(max_digits=12, decimal_places=2,default="15")
total= models.DecimalField(max_digits=12, decimal_places=2,default="20")
class Meta:
verbose_name_plural="Cart Order Items"
def oder_img(self):
return mark_safe('<img src="/media/%s" width="50" height="50"/>'%(self.image))
###########################Product Revew, wishlist, Address############################################
class ProductReview(models.Model):
user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
product=models.ForeignKey(Product, on_delete=models.SET_NULL ,null=True)
review=models.TextField()
rating = models.BigIntegerField(choices=RATING, default=3)
date=models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural="Product Reviews"
def __str__(self):
return self.product.title
def get_rating(self):
return self.rating
class wishlist(models.Model):
user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
product=models.ForeignKey(Product, on_delete=models.SET_NULL ,null=True)
date=models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural="wishlists"
def __str__(self):
return self.product.title
class Address(models.Model):
user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
address=models.CharField(max_length=100, null=True)
status=models.BooleanField(default=False)
class Meta:
verbose_name_plural="Address"
and in admin.py:
from django.contrib import admin
from core.models import *
# Register your models here.
class ProductImagesAdmin(admin.TabularInline):
model= ProductImages
class ProductAdmin(admin.ModelAdmin):
inlines=[ProductImagesAdmin]
list_display=['user','title','product_image','price','featured','product_status']
class CategoryAdmin(admin.ModelAdmin):
list_display=['title','catagory_image']
class VendorAdmin(admin.ModelAdmin):
list_display=['title','Vendor_image']
class CartOrderAdmin(admin.ModelAdmin):
list_display=['user','price','paid_status','order_date','product_status']
class CartOrderItemsAdmin(admin.ModelAdmin):
list_display=['order','invoice_num','product_status','item','image','qty','price','total']
class ProductReviewAdmin(admin.ModelAdmin):
list_display=['user','product','review','rating','date']
class wishlistAdmin(admin.ModelAdmin):
list_display=['user','product','date']
class AddressAdmin(admin.ModelAdmin):
list_display=['user','address','status']
admin.site.register(Product,ProductAdmin)
admin.site.register(Category,CategoryAdmin)
admin.site.register(Vendor,VendorAdmin)
admin.site.register(CartOrder,CartOrderAdmin)
admin.site.register(CartOrderItems,CartOrderItemsAdmin)
admin.site.register(ProductReview,ProductReviewAdmin)
admin.site.register(wishlist,wishlistAdmin)
admin.site.register(Address,AddressAdmin)
in app(name is userauths)-> models.py
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.utils.translation import gettext_lazy as _
# Create your models here.
class CustomUserManager(BaseUserManager):
"""Define a model manager for User model with no username field."""
def _create_user(self, email, password=None, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password=None, **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)
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 CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
See in app(userauths) in model.py there is a
Class CustomUser
But still I am getting Error:
OperationalError at /admin/login/
no such table: userauths_customuser
please help me to figure it out.I make some models and then register it and then apply all the migrations command and it worken but when I am ran "python manage.py runserver" command and then go to the admin pannel there is the error
I created a similar django app, with exactly the files you mentioned and the structure I deduced from your settings.py listing above, and for my luck, I could reproduce the issue.
And immediately it hit me... You did not define any migrations in the userauths app. Without any migrations in the app, makemigrations will not generate any code related to that app, and migrate will not create the table. But when you run the code, the app tries to access data from the table, because you define a custom AUTH_USER_MODEL in settings.py.
So the solution could be one of two things:
Solution 1:
force Django to create the table, use the --run-syncdb flag with the migrate command as described here
python manage.py migrate --run-syncdb
Solution 2:
Add a migration file to the userauths app. The preferable solution. you could use the migration to create a default superuser. That would come handy also during deployment.
Generated by Django 4.2 on 2023-12-01 02:30
import django.contrib.auth.models import django.contrib.auth.validators import django.utils.timezone from django.db import migrations from django.db import models
here is an example of such migration:
class Migration(migrations.Migration):
initial = True
dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
]
operations = [
migrations.CreateModel(
name="CustomUser",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("password", models.CharField(max_length=128, verbose_name="password")),
(
"last_login",
models.DateTimeField(
blank=True, null=True, verbose_name="last login"
),
),
(
"is_superuser",
models.BooleanField(
default=False,
help_text="Designates that this user has all permissions without explicitly assigning them.",
verbose_name="superuser status",
),
),
(
"username",
models.CharField(
error_messages={
"unique": "A user with that username already exists."
},
help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
max_length=150,
unique=True,
validators=[
django.contrib.auth.validators.UnicodeUsernameValidator()
],
verbose_name="username",
),
),
(
"first_name",
models.CharField(
blank=True, max_length=150, verbose_name="first name"
),
),
(
"last_name",
models.CharField(
blank=True, max_length=150, verbose_name="last name"
),
),
(
"email",
models.EmailField(
blank=True, max_length=254, verbose_name="email address"
),
),
(
"is_staff",
models.BooleanField(
default=False,
help_text="Designates whether the user can log into this admin site.",
verbose_name="staff status",
),
),
(
"is_active",
models.BooleanField(
default=True,
help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
verbose_name="active",
),
),
(
"date_joined",
models.DateTimeField(
default=django.utils.timezone.now, verbose_name="date joined"
),
),
(
"groups",
models.ManyToManyField(
blank=True,
help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
related_name="user_set",
related_query_name="user",
to="auth.group",
verbose_name="groups",
),
),
(
"user_permissions",
models.ManyToManyField(
blank=True,
help_text="Specific permissions for this user.",
related_name="user_set",
related_query_name="user",
to="auth.permission",
verbose_name="user permissions",
),
),
],
options={
"verbose_name": "user",
"verbose_name_plural": "users",
"abstract": False,
},
managers=[
("objects", CustomUserManager()),
],
),
]
Solution 3:
Create the table manually by interacting with the DB directly. In your case you are using sqlite3. You can use an sqlite3 client to create the table in the sqlite3 db file.