I've created two models. When I run makemigrations, I'm getting the following error:
ERRORS:
userorders.UserCartItem: (fields.E336) The model is used as an intermediate model by 'userorders.UserCart.items', but it does not have a foreign key to 'UserCart' or 'UserService'.
models.py
class UserCartItem(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
cart = models.ForeignKey("UserCart", on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
line_item_total = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return str(self.id)
class UserCart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
items = models.ManyToManyField(UserService, through=UserCartItem)
items_total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)
def __str__(self):
return str(self.id)
Any thoughts on what the problem is? I've defined the foreign key on UserCartItem as UserCart, but it looks like it's not being recognized. I should point out that I understand that when you identify another model as a foreign key and the foreign key model is below the model that you are working in, you have to put the foreign key model in quotation marks, hence why I used quotation marks in this line:
models.ForeignKey("UserCart", on_delete=models.CASCADE)
thanks!
Had to add default=None:
models.ForeignKey("UserCart", on_delete=models.CASCADE, default=None)
Related
So I am trying to build an inventory system.
I have 2 models, Categories and Product connected through the ManyToMany field.
I want to add a category while I am adding the product just like it happens in the Django admin form.
How can I do that?
My model.py File
class Categories(models.Model):
name = models.CharField(max_length=30)
organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
def __str__(self):
return f"{self.name}"
class Product(models.Model):
category = models.ManyToManyField(Categories)
brand = models.CharField(max_length=20)
model = models.CharField(max_length=20)
hac = models.CharField(max_length=20, null=True, blank=True)
rate = models.DecimalField(max_digits=6, decimal_places=2)
stock = models.IntegerField(default=0)
# organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
date_added = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.brand} {self.model} "
My form.py file
class ProductModelForm(forms.ModelForm):
class Meta:
model = Product
fields = '__all__'
**My code output **
See the below screenshots to understand what I want to do. I basically want that plus button option to add a category from the product form itself.
You should show snippets of codes that we need to provide an answer.
I am trying to delete from Django admin all the products which are stored in PostgresSQL database but getting that error for one product:
IntegrityError at /admin/products/product/
update or delete on table "products_product" violates foreign key constraint "products_curateprodu_product_id_ec2cf1ec_fk_products_" on table "products_curateproducts_products"
DETAIL: Key (id)=(72) is still referenced from table "products_curateproducts_products".
I am not able to figure out why it shows that error while under Curranted Products in Django admin I don´t have any products. At least it won´t show there any, just 0 Curated Products.
Code is here for the Product model:
class Product(models.Model):
seller = models.ForeignKey(SellerAccount, on_delete=models.CASCADE)
media = models.ImageField(blank=True,
null=True,
upload_to=download_media_location,
storage=FileSystemStorage(location=settings.PROTECTED_ROOT))
title = models.CharField(max_length=150)
slug = models.SlugField(blank=True, unique=True)
description = models.TextField(max_length=200, null=True)
price = models.DecimalField(max_digits=10, decimal_places=2, default=9.99, null=True)
sale_active =models.BooleanField(default=False)
sale_price = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True)
def __str__(self):
return self.title
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
ordering = ['title']
and code for Curated Products model:
class CuratedProducts(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
section_name = models.CharField(max_length=20, null=True, blank=True)
products = models.ManyToManyField(Product, blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.section_name
class Meta:
verbose_name = 'Curated Product'
verbose_name_plural = 'Curated Products'
Update, using:
Django 3.0.5,
psycopg2-binary 2.8.5
The error message is showing:
DETAIL: Key (id)=(72) is still referenced from table "products_curateproducts_products".
Note the name curateproducts_products. That does match the model you show. There is another table in the mix.
I have three models as follows in a Django app named markets:
class Market(models.Model):
title = models.CharField(max_length=50, default="")
current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.50)
description = models.TextField(default="")
shares_yes = models.IntegerField(default=0)
shares_no = models.IntegerField(default=0)
b = models.IntegerField(default=100)
cost_function = models.IntegerField(default=0)
open = models.BooleanField(default=True)
def __str__(self):
return self.title[:50]
def get_absolute_url(self):
return reverse('market_detail', args=[str(self.id)])
class Price(models.Model):
market = models.ForeignKey(
Market,
on_delete=models.CASCADE,
related_name='prices',
default=None)
price = models.DecimalField(
max_digits=5,
decimal_places=2,
default=0.50)
price_date = models.DateTimeField(
default=now,
blank=True)
def __str__(self):
return str(self.price)
def get_absolute_url(self):
return reverse('market_list')
class Share(models.Model):
user = models.ForeignKey('users.CustomUser',
on_delete=models.CASCADE,
related_name='user_shares',
default=None)
market = models.ForeignKey(
Market,
on_delete=models.CASCADE,
related_name='market_shares',
default=None)
share = models.IntegerField(default=0)
transaction_date = models.DateTimeField(
default=now,
blank=True)
def __str__(self):
return str(self.share)
def get_absolute_url(self):
return reverse('market_list')
I would like to add the following foreign key field to the Price model:
user = models.ForeignKey('users.CustomUser',
on_delete=models.CASCADE,
related_name='user_prices',
default=None)
When I run makemigrations on markets, there's no issue. But when I try to actually migrate the database, I get the following error:
django.db.utils.IntegrityError: column "user_id" contains null values
Why is that? I had no issues adding a user field to the Share model, so am not clear on why I run into problems when also looking to add it to Price.
When I run makemigrations on markets, there's no issue. But when I try
to actually migrate the database, I get the following error:
django.db.utils.IntegrityError: column "user_id" contains null values
Why is that?
A ForeignKey is by default non-NULLable. But you specify a default=None. The migraiton thus aims to insert NULL for the existing records, and that will fail.
You can make your ForeignKey nullable with:
user = models.ForeignKey('users.CustomUser',
on_delete=models.CASCADE,
related_name='user_prices',
null=True,
default=None
)
You will need to remove (or alter) the migration file, and recreate a migration file.
Another way to resolving this is providing a CustomUser object to which you link the existing records, with that user.
Note: usually it is better to use get_user_model() [Django-doc] instead of providing the user model as a reference or string. If you later change your mind, you can alter the setting, and then all ForeignKeys will be remapped on the new user model.
I've got the following models. I need to obtain a queryset of orders where the user's userprofile.setupstatus == 1. Is this possible or should I just add a foreign key field on the Order model to the UserProfile?
class Order(models.Model):
user = models.ForeignKey(UserCheckout, null=True, on_delete=models.CASCADE)
class UserCheckout(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
setupstatus = models.IntegerField(default=0)
It is surely possible with Django ORM
Your query should look somewhat like this
Order.objects.filter(user__user__userprofile__setupstatus=1)
foreign key field in admin model is not being validated at client side by parsley.
These are my models
class Head(models.Model):
name = models.CharField(max_length=25, blank=False, unique=True)
def __unicode__(self):
return self.name
class Subject(models.Model):
head = models.ForeignKey(Head, blank=False)
name = models.CharField(max_length=25, blank=False, unique=True)
def __unicode__(self):
return self.name
while adding subject name field shows error if it is blank ,but it allows the head field with blank value