I'm trying to create a form view - django

I'm trying to create a Formview wait.
First of all where should I create the Meta class? I saw a page first where it create the Meta class inside the models but then I saw another page where it says that I should create in my forms. So I did that also and then I saw another page where it say that it must register the models in admin because I also had that error where it show an error if I miss an "s" in Meta class models description.
Here's my error:
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /registry.py", line 77, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /urls.py", line 23, in check_resolver
return check_method()
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 446, in check
for pattern in self.url_patterns:
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 632, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 625, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/home/laboratory-01/Desktop/folder1/School/School/urls.py", line 18, in <module>
from principal.views import *
File "/home/laboratory-01/Desktop/folder1/School/principal/views.py", line 7, in <module>
from .forms import *
File "/home/laboratory-01/Desktop/folder1/School/principal/forms.py", line 26, in <module>
class RegForm(ModelForm):
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/forms/models.py", line 259, in __new__
fields = fields_for_model(
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/forms/models.py", line 148, in fields_for_model
opts = model._meta
AttributeError: 'tuple' object has no attribute '_meta'
And here's my forms:
class RegForm(ModelForm):
class Meta:
model = Users
fields = ['name', 'lname1']
Nombre = forms.CharField(label="Nombre", max_length=100, required=False)
ApellidoPaterno = forms.CharField(max_length=100, required=False)
ApellidoMaterno = forms.CharField(max_length=100, required=False)
User = forms.ChoiceField(label="Eres?", choices=Users)
lugarDeNacimiento = forms.ChoiceField(label="Pais", choices=Paises)
FechaNacimiento = forms.DateField(label="Fecha de Nacimiento", initial=datetime.date.today)
foto = forms.ImageField(label="foto")
Email = forms.EmailField(required=True)
passwd = forms.CharField(label="contraseña",max_length=32,widget=forms.PasswordInput)
ConfPasswd = forms.CharField(label="confirmar contraseña", max_length=100, widget=forms.PasswordInput)
And here's my models where I also put the formclass. I don't know why:
class Users(models.Model):
name = models.CharField(max_length=100, primary_key=True)
lname1 = models.CharField(max_length=100)
lname2 = models.CharField(max_length=100)
age = models.IntegerField()
user_name = models.CharField(max_length=12, choices=users)
imagen = models.ImageField()
birthday = models.DateField(auto_now_add=False)
country = models.CharField(max_length=12, choices=paises)
Email = models.EmailField( )
idCard = models.IntegerField()
psswd = models.CharField(max_length=90)
conf_psswd = models.CharField(max_length=100)
def __str__(self):
return self.nombre
class RegForm(ModelForm):
class Meta:
Model = Users
or am I registering the models wrong in the admin file because I also have to say that I have three applications in a project it's profesores estudiantes principal where principal should be my authentication tools of Django.

Related

Cannot create database after messing with squashmigrations

I have run squashmigrations in Django and after a while I needed to delete the database and start from scratch (the problem also applies when downloading the repository from GitHub and trying to recreate the project). I get following error when running python manage.py makemigrations or python manage.py migrate:
(venv) meal_plan   main  python manage.py makemigrations
Traceback (most recent call last):
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: meal_plan_recipe
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/enricobonardi/CODING/TESTING/meal_plan/manage.py", line 22, in <module>
main()
File "/Users/enricobonardi/CODING/TESTING/meal_plan/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 443, in execute
self.check()
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 475, in check
all_issues = checks.run_checks(
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 42, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 61, in _load_all_namespaces
url_patterns = getattr(resolver, "url_patterns", [])
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 715, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 708, in urlconf_module
return import_module(self.urlconf_name)
File "/Users/enricobonardi/.pyenv/versions/3.10.7/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Users/enricobonardi/CODING/TESTING/meal_plan/config/urls.py", line 9, in <module>
path("", include("meal_plan.urls", namespace="mealplan")),
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/urls/conf.py", line 38, in include
urlconf_module = import_module(urlconf_module)
File "/Users/enricobonardi/.pyenv/versions/3.10.7/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Users/enricobonardi/CODING/TESTING/meal_plan/meal_plan/urls.py", line 5, in <module>
from . import views
File "/Users/enricobonardi/CODING/TESTING/meal_plan/meal_plan/views.py", line 11, in <module>
from .forms import MealPlanForm, RecipeSimpleForm
File "/Users/enricobonardi/CODING/TESTING/meal_plan/meal_plan/forms.py", line 26, in <module>
class RecipeSimpleForm(forms.ModelForm):
File "/Users/enricobonardi/CODING/TESTING/meal_plan/meal_plan/forms.py", line 38, in RecipeSimpleForm
RECIPES = [(x.id, x.title) for x in Recipe.objects.all()]
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/models/query.py", line 394, in __iter__
self._fetch_all()
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1866, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/models/query.py", line 87, in __iter__
results = compiler.execute_sql(
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1398, in execute_sql
cursor.execute(sql, params)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 103, in execute
return super().execute(sql, params)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute
with self.db.wrap_database_errors:
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: meal_plan_recipe
(venv) ✘  meal_plan   main 
meal_plan/models.py:
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.urls import reverse
User = settings.AUTH_USER_MODEL
# ---------Stagionality----------#
class Month(models.Model):
name = models.CharField(max_length=25)
class Meta:
ordering = ("id",)
verbose_name = "mese"
verbose_name_plural = "mesi"
def __str__(self):
return self.name
class VegetableItem(models.Model):
class Types(models.IntegerChoices):
VERDURA = 1
FRUTTA = 2
name = models.CharField(max_length=100)
type = models.SmallIntegerField(choices=Types.choices, default=Types.VERDURA)
description = models.TextField(blank=True)
seasonality = models.ManyToManyField(Month, verbose_name="stagionalità")
image = models.ImageField(upload_to="vegetableitems", default="vegetableitems/default.png")
class Meta:
verbose_name = "alimento stagionale"
verbose_name_plural = "alimenti stagionali"
def __str__(self):
return self.name
# ---------END of Stagionality----------#
# ---------MealPlan----------#
class Day(models.TextChoices):
LUNEDI = "LUN", "Lunedì"
MARTEDI = "MAR", "Martedì"
MERCOLEDI = "MER", "Mercoledì"
GIOVEDI = "GIO", "Giovedì"
VENERDI = "VEN", "Venerdì"
SABATO = "SAB", "Sabato"
DOMENICA = "DOM", "Domenica"
class Type(models.IntegerChoices):
COLAZIONE = 1
SPUNTINO = 2
PRANZO = 3
MERENDA = 4
CENA = 5
class MealPlan(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self) -> str:
return self.title
class Meta:
verbose_name_plural = "mealplan"
def get_absolute_url(self):
return reverse("mealplan:mealplan_detail", kwargs={"pk": self.pk})
class Meal(models.Model):
day = models.CharField(max_length=3, choices=Day.choices, default=Day.LUNEDI, verbose_name="giorno")
type = models.IntegerField(choices=Type.choices)
mealplan = models.ForeignKey(MealPlan, on_delete=models.CASCADE)
class Meta:
verbose_name = "pasto"
verbose_name_plural = "pasti"
def __str__(self) -> str:
return f"{self.mealplan} ({self.get_day_display()} - {self.get_type_display()})"
class Measure(models.IntegerChoices):
ML = 1
G = 2
UNIT = 3
class Recipe(models.Model):
title = models.CharField(max_length=100)
method = models.TextField(blank=True)
meals = models.ManyToManyField(Meal)
class Meta:
verbose_name = "ricetta"
verbose_name_plural = "ricette"
def __str__(self) -> str:
return self.title
class Ingredient(models.Model):
name = models.CharField(max_length=100)
quantity = models.SmallIntegerField(blank=True)
measure = models.IntegerField(choices=Measure.choices, default=Measure.G)
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True)
#receiver(post_save, sender=MealPlan)
def mealplan_post_save_receiver(sender, instance, created, *args, **kwargs):
if created:
mealplan = instance
days_of_the_week = Meal._meta.get_field("day").choices
days = [label for label, day in days_of_the_week]
for day in days:
for type in range(1, 6):
meal = Meal.objects.create(mealplan=mealplan, day=day, type=type)
meal.save()
# ---------END of MealPlan----------#
I tried to reset migrations on original repository using these instructions with no luck.
Finally found the bug causing the migration error. It's not about the squashmigrations command but in forms.py
class RecipeSimpleForm(forms.ModelForm):
...
RECIPES = [(x.id, x.title) for x in Recipe.objects.all()]
title = forms.ChoiceField(widget=forms.Select, choices=RECIPES)
class Meta:
model = Recipe
fields = ["title"]
I think the problem is I'm calling Recipe.objects.all() before the DB was created.
Simply delete your all migration folders and re-migrate manually using below command:
python manage.py makemigrations appname
python manage.py sqlmigrate appname 0001
python manage.py migrate
And see if it solves your error

Django django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

So I'm trying to integrate a model with mongoDB usng djongo driver, and when I tried to insert a record from within models.py it is giving me this error.I'm a newbie and trying to get my hands on django. Please have a look and explain that where and why I'm wrong/ Thank you.
AppRegistryNotReady("Models aren't loaded yet.")
here are my code files.
models.py
from djongo import models
class Iname(models.Model):
item_name = models.TextField()
class Meta:
abstract = True
class Iquantity(models.Model):
item_quantity = models.FloatField()
class Meta:
abstract = True
class Iprice(models.Model):
item_price = models.FloatField()
class Meta:
abstract = True
class Order(models.Model):
email = models.EmailField(primary_key = True, name = "email")
name = models.CharField(max_length=30, help_text="Enter Customer Name", name = "name")
address = models.TextField(help_text="Enter customer's Address", name = "address")
item_names = models.ArrayField(model_container = Iname)
item_quantities = models.ArrayField(model_container = Iquantity)
item_prices = models.ArrayField(model_container = Iprice)
objects = models.DjongoManager()
o = Order()
o.email = "jayesh#gmail.com"
o.name = "dhsdb"
o.address = "agdkhdvf"
o.item_names = ['chocolate', 'pencil']
o.item_quantities = [5, 10]
o.item_prices = [10, 3]
o.save()
serializers.py
from .models import Order, Iname, Iprice, Iquantity
from rest_framework import serializers
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Iname
class QuantitySerializer(serializers.ModelSerializer):
class Meta:
model = Iquantity
class PriceSerializer(serializers.ModelSerializer):
class Meta:
model = Iprice
class OrderSerializer(serializers.ModelSerializer):
item_names = ItemSerializer()
item_quantities = QuantitySerializer()
item_prices = PriceSerializer()
class Meta:
model = Order
fields = "__all__"
views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import OrderSerializer
from .models import Order
#api_view(['GET',])
def get_orders(request):
orders = Order.objects.all()
serializer = OrderSerializer(instance = orders, many = True)
print(serializer.data)
return Response(data = serializer.data)
And yes here is my traceback
C:\Users\ACER\Desktop\invoice\base\models.py changed, reloading.
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "c:\users\acer\anaconda3\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "c:\users\acer\anaconda3\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run
autoreload.raise_last_exception()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
raise _exception[1]
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\core\management\__init__.py", line 398, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\apps\registry.py", line 116, in populate
app_config.import_models()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\apps\config.py", line 304, in import_models
self.models_module = import_module(models_module_name)
File "c:\users\acer\anaconda3\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\ACER\Desktop\invoice\base\models.py", line 64, in <module>
o.save()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\base.py", line 857, in save_base
updated = self._save_table(
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\base.py", line 970, in _save_table
updated = self._do_update(
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\base.py", line 1034, in _do_update
return filtered._update(values) > 0
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\query.py", line 885, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\sql\compiler.py", line 1783, in execute_sql
cursor = super().execute_sql(result_type)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\sql\compiler.py", line 1348, in execute_sql
sql, params = self.as_sql()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\sql\compiler.py", line 1749, in as_sql
val = field.get_db_prep_save(val, connection=self.connection)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\djongo\models\fields.py", line 229, in get_db_prep_save
processed_value = self._save_value_thru_fields('get_db_prep_save',
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\djongo\models\fields.py", line 344, in _save_value_thru_fields
post_dict = super()._save_value_thru_fields(func_name,
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\djongo\models\fields.py", line 155, in _save_value_thru_fields
for field in self.model_container._meta.get_fields():
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\options.py", line 849, in get_fields
return self._get_fields(
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\options.py", line 928, in _get_fields
all_fields = self._relation_tree
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\utils\functional.py", line 49, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\options.py", line 822, in _relation_tree
return self._populate_directed_relation_graph()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\db\models\options.py", line 789, in _populate_directed_relation_graph
all_models = self.apps.get_models(include_auto_created=True)
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\apps\registry.py", line 181, in get_models
self.check_models_ready()
File "C:\Users\ACER\Desktop\invoice\env\lib\site-packages\django\apps\registry.py", line 143, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
list of dependencies i'm using
asgiref==3.5.2
backports.zoneinfo==0.2.1
Django==4.0.5
djangorestframework==3.13.1
djongo==1.3.6
pymongo==3.12.3
pytz==2022.1
sqlparse==0.2.4
tzdata==2022.1

(Django Migration Bug with PostgreSQL) django.db.utils.ProgrammingError: relation "subjects_subject" does not exist

**Link github to this repo : **https://github.com/thetruefuss/elmer
When i start this project using sqlite for database, it migrate with database perfectly, but when i switch it to POSTGRESQL, it got this error:
django.db.utils.ProgrammingError: relation "subjects_subject" does not exist
LINE 1: ...ect"."created", "subjects_subject"."updated" FROM "subjects_...
THE POINT IS: in this repo it already had all the migrations file for all model, u can check in this repo, and i cannot migrate this with database in pgadmin 4
db settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'demo_postgres',
'USER':'postgres',
'PASSWORD':'18092000',
'PORT':'5432',
'HOST':'127.0.0.1',
}
}
** my command **
python manage.py migrate
subjects_subject ( migration_file)
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('boards', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Subject',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(db_index=True, max_length=150)),
('slug', models.SlugField(blank=True, max_length=150, null=True)),
('body', models.TextField(blank=True, max_length=5000, null=True)),
('photo', models.ImageField(blank=True, null=True, upload_to='subject_photos/', verbose_name='Add image (optional)')),
('rank_score', models.FloatField(default=0.0)),
('active', models.BooleanField(default=True)),
('created', models.DateTimeField(default=django.utils.timezone.now)),
('updated', models.DateTimeField(auto_now=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posted_subjects', to=settings.AUTH_USER_MODEL)),
('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='submitted_subjects', to='boards.Board')),
('mentioned', models.ManyToManyField(blank=True, related_name='m_in_subjects', to=settings.AUTH_USER_MODEL)),
('points', models.ManyToManyField(blank=True, related_name='liked_subjects', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('-created',),
},
),
]
subjects_subject(model_file)
class Subject(models.Model):
"""
Model that represents a subject.
"""
title = models.CharField(max_length=150, db_index=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
body = models.TextField(max_length=5000, blank=True, null=True)
photo = models.ImageField(
upload_to='subject_photos/', verbose_name=u"Add image (optional)",
blank=True, null=True
)
author = models.ForeignKey(User, related_name='posted_subjects', on_delete=models.CASCADE)
board = models.ForeignKey(Board, related_name='submitted_subjects', on_delete=models.CASCADE)
points = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name='liked_subjects', blank=True
)
mentioned = models.ManyToManyField(
User, related_name='m_in_subjects', blank=True
)
rank_score = models.FloatField(default=0.0)
active = models.BooleanField(default=True)
created = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created',)
EDIT : 1 (FULL TRACEBACK)
File "E:\Python\elmer\manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "E:\Python\elmer\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "E:\Python\elmer\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "E:\Python\elmer\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "E:\Python\elmer\venv\lib\site-packages\django\core\management\base.py", line 350, in execute
self.check()
File "E:\Python\elmer\venv\lib\site-packages\django\core\management\base.py", line 376, in check
all_issues = self._run_checks(
File "E:\Python\elmer\venv\lib\site-packages\django\core\management\commands\migrate.py", line 60, in _run_checks
issues.extend(super()._run_checks(**kwargs))
File "E:\Python\elmer\venv\lib\site-packages\django\core\management\base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "E:\Python\elmer\venv\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "E:\Python\elmer\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "E:\Python\elmer\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "E:\Python\elmer\venv\lib\site-packages\django\urls\resolvers.py", line 396, in check
for pattern in self.url_patterns:
File "E:\Python\elmer\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "E:\Python\elmer\venv\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "E:\Python\elmer\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "E:\Python\elmer\venv\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "E:\Python\elmer\mysite\urls.py", line 33, in <module>
import subjects.views as subjects_views
File "E:\Python\elmer\subjects\views.py", line 58, in <module>
class TrendingPageView(ListView):
File "E:\Python\elmer\subjects\views.py", line 63, in TrendingPageView
queryset = get_trending_subjects()
File "E:\Python\elmer\subjects\views.py", line 25, in get_trending_subjects
for subject in subjects:
File "E:\Python\elmer\venv\lib\site-packages\django\db\models\query.py", line 268, in __iter__
self._fetch_all()
File "E:\Python\elmer\venv\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "E:\Python\elmer\venv\lib\site-packages\django\db\models\query.py", line 54, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "E:\Python\elmer\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1065, in execute_sql
cursor.execute(sql, params)
File "E:\Python\elmer\venv\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "E:\Python\elmer\venv\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "E:\Python\elmer\venv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "E:\Python\elmer\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "E:\Python\elmer\venv\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "E:\Python\elmer\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "subjects_subject" does not exist
LINE 1: ...ect"."created", "subjects_subject"."updated" FROM "subjects_...
^
Your problem is that you are executing database queries in the start-up of your app, this causes a lot of issues with migrations and is generally discouraged.
In the body of the TrendingPageView class you are calling get_trending_subjects() which is executing a query on the Subject model, you need to move this to a method so that it is not called on start-up but when the view is accessed.
class TrendingPageView(ListView):
model = Subject
paginate_by = 15
template_name = 'subjects/trending.html'
context_object_name = 'subjects'
def get_queryset(self):
return get_trending_subjects()

Can't identify problem in my serializers.py file

I can't figure out why I'm getting errors. If I don't import the serializers.py file then the error goes (my views don't yet make use of this file).
Serializers.py:
from rest_framework import serializers
# This file is the equivilent of forms.py in that we define models to serialise.
class MerchantSerializer(serializers.Serializer):
id = serializers.CharField(required=True, max_length=50)
name = serializers.CharField(required=True, max_length=100)
logo = serializers.URLField(max_length=250, required=False)
class DataSerializer(serializers.Serializer):
account_id = serializers.CharField(required=True, max_length=50)
amount = serializers.IntegerField(required=True, min_value=0)
created = serializers.DateTimeField()
currency = serializers.CharField(required=True, max_length=3)
description = serializers.CharField(required=True, max_length=250)
id = serializers.CharField(required=True, max_length=50)
category = serializers.CharField(required=True, max_length=100)
is_load = serializers.BooleanField()
settled = serializers.DateTimeField()
merchant = serializers.ListField(child=MerchantSerializer)
class TransactionSerializer(serializers.Serializer):
type = serializers.CharField(required=True, max_length=50)
data = serializers.ListField(child=DataSerializer)
My view isn't doing anything yet. Plan was to just receive some JSon to create my webhook, validate the JSON and then save the data. The JSON contains objects that span several models and the field names won't match the models so I don't think I can use any model serializers.
Views.py:
from django.shortcuts import render
from django.contrib.auth.models import User
from rest_framework import viewsets
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
import datetime
from .models import Transaction
from .serializers import TransactionSerializer
#Enable logging
import logging
logger = logging.getLogger(__name__)
# Create your views here.
#csrf_exempt
def index(request):
data = json.loads(request.body)
return render(request, 'template.html', )
Traceback:
python manage.py runserver 80
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\philip\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\philip\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = self._run_checks(
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\urls\resolvers.py", line 407, in check
for pattern in self.url_patterns:
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\philip\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\philip\CodeRepos\MonzoWebHook\monzowebhook\urls.py", line 6, in <module>
import core.views
File "C:\Users\philip\CodeRepos\MonzoWebHook\core\views.py", line 9, in
<module>
from .serializers import TransactionSerializer
File "C:\Users\philip\CodeRepos\MonzoWebHook\core\serializers.py", line
10, in <module>
class DataSerializer(serializers.Serializer):
File "C:\Users\philip\CodeRepos\MonzoWebHook\core\serializers.py", line
20, in DataSerializer
merchant = serializers.ListField(child=MerchantSerializer)
File "C:\Users\philip\CodeRepos\MonzoWebHook\venv\lib\site-packages\rest_framework\fields.py", line 1646, in __init__
assert not inspect.isclass(self.child), '`child` has not been instantiated.'
AssertionError: `child` has not been instantiated.
You need to add parantheses after setting childs.
data = serializers.ListField(child=DataSerializer())
merchant = serializers.ListField(child=MerchantSerializer())

How to make choices based on the model? - Models aren't loaded yet. FK issue (seems to be)

Read all topics at StackOverflow and internet - no luck.
# admindivisions.models
class Countries(models.Model):
osm_id = models.IntegerField(db_index=True, null=True)
status = models.IntegerField()
population = models.IntegerField(null=True)
iso3166_1 = models.CharField(max_length=2, blank=True)
iso3166_1_a2 = models.CharField(max_length=2, blank=True)
iso3166_1_a3 = models.CharField(max_length=3, blank=True)
class Meta:
db_table = 'admindivisions_countries'
verbose_name = 'Country'
verbose_name_plural = 'Countries'
class CountriesTranslations(models.Model):
common_name = models.CharField(max_length=81, blank=True, db_index=True)
formal_name = models.CharField(max_length=100, blank=True)
country = models.ForeignKey(Countries, on_delete=models.CASCADE, verbose_name='Details of Country')
lang_group = models.ForeignKey(LanguagesGroups, on_delete=models.CASCADE, verbose_name='Language of Country',
null=True)
class Meta:
db_table = 'admindivisions_countries_translations'
verbose_name = 'Country Translation'
verbose_name_plural = 'Countries Translations'
# profiles.models
from admindivisions.models import CountriesTranslations, Countries
class AbstractProfile(models.Model):
COUNTRY_CHOICES = ()
if (Languages.objects.model._meta.db_table in connection.introspection.table_names()):
# Just for test - This executes without any errors
CountriesTranslations.objects.filter(common_name="USA")
for country in Countries.objects.filter(status=1).exclude(iso3166_1='', iso3166_1_a2=''):
# Just for test - Also executes ok
CountriesTranslations.objects.get(common_name="USA")
# Makes problem (seems to be because of FK)
country_name = CountriesTranslations.objects.get(country=country)
COUNTRY_CHOICES += ((country.id, country_name),)
country = models.ForeignKey(Countries, verbose_name=_('country'), choices=COUNTRY_CHOICES, blank=True)
title = models.CharField(_('title'), max_length=30)
info = models.TextField(_('information'), max_length=500, blank=True)
class Meta:
abstract = True
Traceback:
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/antonio/www/sportland/sportland/src/profiles/models.py", line 76, in <module>
class AbstractProfile(models.Model):
File "/home/antonio/www/sportland/sportland/src/profiles/models.py", line 109, in AbstractProfile
country_name = CountriesTranslations.objects.get(country=country)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/query.py", line 376, in get
clone = self.filter(*args, **kwargs)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/query.py", line 796, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/query.py", line 814, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1227, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1253, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1133, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1019, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1308, in names_to_path
if field.is_relation and not field.related_model:
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/fields/related.py", line 111, in related_model
apps.check_models_ready()
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
This happens if I want to execute any manage.pys command.
Coming from few tests above I can guess the problem is due to ForeignKey. How to fix it?
Django 1.10
You mustn't do any logic like that at class level. Obviously you can't query the models until they are all fully loaded.
I don't understand what you are trying to do there, but you should move it into a method.