I am trying to create a cart model using ForeignKey relation with User.
My mall/models.py:
from django.db import models
from django.contrib.auth.models import User
class products(models.Model):
image = models.ImageField(upload_to='products/', blank=True)
name = models.CharField(max_length=100)
detail = models.TextField(max_length=100, verbose_name='detail of product')
price = models.FloatField()
def __str__(self):
return self.name
class cart(models.Model):
item = models.OneToOneField(products, on_delete=models.CASCADE)
user = models.ForeignKey(User, null=True, blank=True, default=None, on_delete=models.CASCADE)
def __str__(self):
return self.item.name
I am getting a error like this:
django.db.utils.IntegrityError: NOT NULL constraint failed: new__mall_cart.user_id
whenever I am trying to migrate it. Its showing the same error if I am migrating the products class alone as well
.
I have provided null=True as well as blank=True and the superuser is created with the name of admin. What is issue here?
Related
I am creating the super user through admin panel or command line, but it is not showing in the custom model in the database.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.TextField(null=True)
profile_image = models.ImageField(null=True, blank=True)
def __str__(self):
return str(self.user)
class Following(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
following = models.CharField(max_length=30)
class Follower(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
follower = models.CharField(max_length=30)
Using OneToOnefield should create the user in the Profile model automatically but it is not happening. I am not sure what is wrong because in the previous project it was workiing fine. Also I have registered the models in admin.py.
So, I am actively trying to create categories with subcategories. My current app is listings, and the idea is to create a ManyToManyField inside my Listing models. Here is my code inside models.py.
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class Category(MPTTModel):
name = models.CharField(max_length=150, unique=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['name']
class Blist(models.Model):
name = models.CharField('Business Name', max_length=250)
address = models.CharField('Address', max_length=300)
city = models.CharField('City', max_length=100)
zip_code = models.CharField('Zip Code', max_length=10)
phone_number = models.CharField('Phone Number', max_length=20)
web = models.URLField('Website')
def __str__(self):
return self.name
But when I go into the shell to add items into the category, I'm getting errors:
django.db.utils.ProgrammingError: column listings_category.name does not exist
LINE 1: SELECT "listings_category"."id", "listings_category"."name",...
Once finished, I ran makemigrations and migrate, but I realize it is not creating the tables in my database. I'm using Postgresql.
What am I doing wrong here?
I am trying to migrate, and view the admin page. both makemigrations and migrate passed, yet when i go to the admin url it reads this: "django.db.utils.OperationalError: no such column: social_app_user.id"
And once i create an id field, it changes to "django.db.utils.OperationalError: no such column: social_app_user.password"
I was under the impression that the AbstractUser model included all the default user fields, not sure about the primary key, but regardless.
Please help, thanks!
Note: the 'id' field in this models.py file was added after i got the error.
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
class User(AbstractUser):
is_verified = models.BooleanField(default=True)
id= models.AutoField(primary_key=True, null=False)
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
f"{self.username} {self.email}"
return
class main_feed(models.Model):
content= models.CharField(unique=True, max_length=255, default='', null=False)
poster = models.ForeignKey('User', related_name='author', on_delete=models.CASCADE, to_field='username')
likes = models.IntegerField(default=0, null=False)
favorites = models.IntegerField(default=0, null=False)
date_posted = models.DateTimeField(auto_now=True)
def __str__(self):
f"{self.content} {self.likes} {self.poster} {self.date_posted}"
return
It turns out I had to restart my entire application and run startapp again.
This time i added the user model and set up the settings and admin file BEFORE the very first migration. then everything works dandy. But I have no idea why this is the case, shouldnt the migration update and override the default user model?
anyways the question is answered now.
I want to show a validation message like "This Project already exists" in my django admin whenever i create a project with same name.
I keep getting an IntegrityError at my Name. Isn't Django supposed to validate this and give an ValidationError if I use unique_together=((,)) in my model? Or do I have to Try and Catch the IntegrityError myself?
Also i have made two users and gave permissions to them from main admin user. so i want that one user1 cannot have projects with same name like proj1 while the user2 can have name of project as proj1.
Can anyone tell me a best practice for validating unique users inside a form/model.
models.py
class Project(models.Model):
name = models.CharField(max_length=200)
added_by = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, default=None)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
unique_together = (("name", "added_by"),)
def __str__(self):
return self.name
I'm pulling my hair out with this. When I attempt to add a 'Product' from my admin page, I'm getting an IntegrityError: main_product.img may not be NULL.
Models.py
class Product(models.Model):
name = models.CharField(max_length=500)
short = models.CharField(max_length=250)
description = models.TextField()
price = models.DecimalField(max_digits=8, decimal_places=2)
in_stock = models.BooleanField()
def __unicode__(self):
return self.name
class ProductImages(models.Model):
product = models.ForeignKey(Product, blank=True)
img = models.ImageField(upload_to='images', blank=True)
caption = models.CharField(max_length=300, blank=True)
class ProductFeatures(models.Model):
product = models.ForeignKey(Product)
feature = models.CharField(max_length=500)
Admin.py
class ProductFeaturesAdmin(admin.TabularInline):
model = ProductFeatures
extra = 1
class ProductImageAdmin(admin.TabularInline):
model = ProductImages
extra = 1
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'price', 'in_stock')
inlines = [ProductFeaturesAdmin, ProductImageAdmin]
admin.site.register(Product,ProductAdmin)
I was using Pillow to resize images when being upload, so I had a custom save() function in my ProductImages model. I removed that thinking it was the problem, but it's still not working. As you can tell, I'm really new to Django and Python. Any and all help appreciated.
Edit: forgot to mention that I've added blank=true and null=true to Product.img, then used South to migrate the table.
Edit 2: This is my new ProductImages model.
class ProductImages(models.Model):
product = models.ForeignKey(Product)
img = models.ImageField(upload_to='images', blank=True, null=True)
caption = models.CharField(max_length=300, blank=True)
I used South and ran:
python manage.py schemamigration main --auto
python manage.py migrate main
Still having the error. If I were to add the img field to my Products model, how would I be able to add multiple imgs in the admin panel?
Actually you need to add null=True in the img field, So make it img = models.ImageField(upload_to='images', blank=True, null=True).
The difference is that because blank=True decides that whether the fields will be required by the forms. blank=False means that field cannot be blank and blank=True means field will not be required.
Regarding null=True sets NULL in column of your DB which will solve your issue.