Model has either not been installed or is abstract - python

When I try to migrate my code I get this error.
Here are my code and classes:
from django.db import models
from core.models import Event
class TicketType(models.Model):
name = models.CharField(max_length=45)
price = models.DecimalField(max_length=2, decimal_places=2, max_digits=2)
type = models.CharField(max_length=45)
amount = models.IntegerField()
event = models.ForeignKey(Event)
class Meta:
app_label = "core"
import datetime
from django.core.serializers import json
from django.db import models
from core.models import User
class Event(models.Model):
page_attribute = models.TextField()
name = models.TextField(max_length=128 , default="New Event")
description = models.TextField(default="")
type = models.TextField(max_length=16)
age_limit = models.IntegerField(default=0)
end_date = models.DateTimeField(default=datetime.datetime.now())
start_date = models.DateTimeField(default=datetime.datetime.now())
is_active = models.BooleanField(default=False)
user = models.ForeignKey(User)
ticket_type=models.ForeignKey('core.models.ticket_type.TicketType')
class Meta:
app_label = "core"
Here is the error I get:
CommandError: One or more models did not validate:
core.event: 'ticket_type' has a relation with model core.models.ticket_type.TicketType,
which has either not been installed or is abstract.

You're unnecessarily confusing yourself by having these in separate files within the same app.
But your issue is caused by the way you're referenced the target model. You don't use the full module path to the model: you just use 'app_name.ModelName'. So in your case it should be:
ticket_type=models.ForeignKey('core.TicketType')

Another issue can be when using multiple models in separate files missing statement like:
class Meta:
app_label = 'core_backend'

You can also get this error if there a bug in your models file that prevents it from loading properly. For example, in models.py
from third_party_module_i_havent_installed import some_method

I hit this error when I didn't put a third-party app in my INSTALLED_APPS setting yet.

Related

The model is not displayed in the django admin panel

I don't have the advertisement module displayed in the django admin panel. Here is the model code
from django.db import models
class Advertisement(models.Model):
title = models.CharField(max_length=1000, db_index=True)
description = models.CharField(max_length=1000, default='', verbose_name='description')
creates_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
price = models.FloatField(default=0, verbose_name="price")
views_count = models.IntegerField(default=1, verbose_name="views count")
status = models.ForeignKey('AdvertisementStatus', default=None, null=True, on_delete=models.CASCADE,
related_name='advertisements')
def __str__(self):
return self.title
class Meta:
db_table = 'advertisements'
ordering = ['title']
class AdvertisementStatus(models.Model):
name = models.CharField(max_length=100)
admin.py /
from django.contrib import admin
from .models import Advertisement
admin.site.register(Advertisement)
I was just taking a free course from YouTube. This was not the case in my other projects. Here I registered the application got the name in INSTALLED_APPS. Then I performed the creation of migrations and the migrations themselves. Then I tried to use the solution to the problem here , nothing helped. I didn't find a solution in Google search either.
127.0.0.1:8000/admin/
console
admins.py
The name of the file is admin.py not admins.py. Yes, that is a bit confusing since most module names in Django are plural. The rationale is probably that you define a (single) admin for the models defined.
Alternatively, you can probably force Django to import this with the AppConfig:
# app_name/apps.py
from django.apps import AppConfig
class AppConfig(AppConfig):
def ready(self):
# if admin definitions are not defined in admin.py
import app_name.admins # noqa

Why is Django giving me a ValueError when I reference a class within the same model?

I'm building a simple recipe app, and so far I have two models: Ingredient and Recipe.
Each recipe should have multiple ingredients, so I laid out my model like this:
class Ingredient(models.Model):
name = models.CharField(max_length=50)
class Recipe(models.Model):
title = models.CharField(max_length=100)
ingredients = models.ForeignKey(Ingredient, on_delete=CASCADE)
instructions = JSONField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=SET_DEFAULT, default='Chef Anon')
When I makemigrations, I get nothing, but when I migrate, I get this ValueError:
ValueError: Cannot alter field cookbook.Recipe.ingredients into cookbook.Recipe.ingredients - they do not properly define db_type (are you using a badly-written custom field?)
Following the example here (Django: Add foreign key in same model but different class), I've tried setting ingredients=models.ForeignKey(Ingredient, on_delete=CASCADE) as well as using lazy syntax ingredients=models.ForeignKey("Ingredient", on_delete=CASCADE), but each time, makemigrations shows no changes, and migrate gives me the same ValueError.
Edit
My imports:
from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
from django.db.models.fields.json import JSONField
from django.utils import timezone
from django.contrib.auth.models import User```
Try replacing on_delete=CASCADE with on_delete=models.CASCADE
If you have not imported CASCADE separately from models.
All though, in that case you should get a warning that "CASCADE is not defined".
I believe I found the problem: My models.py file was in the root directory, not in the app directory.

how to avoid circular django model import?

I have these models below
# user profile models file
from ad.models import FavoriteAd
class UserProfile(models.Model):
def get_user_favorite_ad(self):
return FavoriteAd.objects.filter(fav_user=self)
# ad models file
from user_profile.models import UserProfile
class FavoriteAd(models.Model):
fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE)
I have tried using these but it give me the NameError UserProfile not found
# ad models files
class FavoriteAd(models.Model):
fav_user = models.ForeignKey('user_profile.UserProfile', blank=False, on_delete=models.CASCADE)
Also tried these as well still got error that model are not ready
# ad models files
from django.apps import apps
UserProfile = apps.get_model('user_profile', 'UserProfile')
class FavoriteAd(models.Model):
fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE)
You are using FavoriteAd inside get_user_favorite_ad method of
UserProfile model
Thats the reason you are unable to import it in FavoriteAd and this is causing circular import.
For fetching favorite ads of that user, Use favoritead_set to get related objects
# remove that import as well
# from ad.models import FavoriteAd
class UserProfile(models.Model):
def get_user_favorite_ad(self):
return self.favoritead_set.all()

Unable to migrate Django models

So I'm trying to automatically assign the current logged in user to a variable in my model. I think this make sense but I'm not able to migrate the models and it is going me this error.
models.py:
from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics',blank='True')
def __str__(self):
return self.user.username
class UserPosts(models.Model):
post_title = models.CharField(max_length=100,unique=True)
post_sub_title = models.CharField(max_length=250,unique=False)
post_author = models.ForeignKey('User',User.username)
post_date = models.DateField(default=date.today,blank=True)
post_body = models.TextField(max_length=1000,unique=False)
def __str__(self):
return str(self.post_title)
The Error:
ValueError: Cannot create form field for 'post_author' yet, because its related model 'User' has not been loaded yet
Remove the quotation from this line:
post_author = models.ForeignKey('User',User.username)
It should be like this:
post_author = models.ForeignKey(User,User.username)
I think the problem is this:
from django.contrib.auth.models import User
post_author = models.ForeignKey('User',User.username)
Your ForeignKey want's to use the attribute 'username' of the imported User. Not of your User object when related.
I think I just deleted the migrations and then migrated again from scratch...

NameError at / name 'article_finish_date' is not defined

So I am trying to create a custom Manager that extends the default one and I am getting an error that for the life of me I cannot fix. I've read all the django docs and can't see what I've done wrong!
ERROR:
NameError at /
name 'article_finish_date' is not defined
Here is my models.py
import datetime
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class ArticleManager(models.Manager):
def get_queryset(self):
return super(ArticleManager, self).get_queryset().filter(article_finish_date==None)
class Article(models.Model):
article_name_text = models.CharField(max_length=200)
article_creation_date = models.DateTimeField('date created')
article_publish_date = models.DateTimeField('date published', null=True, blank=True)
article_finish_date = models.DateTimeField('date finished', null=True, blank=True)
def __str__(self):
return self.article_name_text
actives = ArticleManager()
I have tried filtering by all the different values of the Article model, however the same issue occurs. I have tried both migrated and makemigrations, however no progress has been made.
Many thanks in advance, ask if you need more details!
The error is in this part:
.filter(article_finish_date==None)
Python is trying to evaluate the expression article_finish_date==None, except article_finish_date hasn't been defined yet. Instead, you want to use a single =
.filter(article_finish_date=None)

Categories