I'm trying to replicate a PHP/Symfony project in Python/Django as a python learning exercise. Platform = Windows 10. The expected result is that a migrate command will add tables related to all of the entries in settings.py INSTALLED_APPS{...}. Instead, the migrate command adds all Django tables but none of the tables of models.py.
What, then, must be done to allow migrate to add the 5 MySQL tables?
Result:
mysql> use diet_py;
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_diet_py |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
+----------------------------+
Following Django tutorial documentation, with slight modifications, I have these directories & files:
Tree:
...DB1-PROJECT
│ db.sqlite3
│ manage.py
│
├───diet
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ │ __init__.py
│ │ │
│ │ └───__pycache__
│ │ __init__.cpython-311.pyc
│ │
│ └───__pycache__
│ admin.cpython-311.pyc
│ apps.cpython-311.pyc
│ models.cpython-311.pyc
│ __init__.cpython-311.pyc
│
└───mysite
│ asgi.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└───__pycache__
settings.cpython-311.pyc
urls.cpython-311.pyc
wsgi.cpython-311.pyc
__init__.cpython-311.pyc
..\diet\models.py
from django.db import models
# Create your models here.
from django.db import models
class Food(models.Model):
food_name = models.CharField(max_length=255)
class Meta:
db_table = 'food'
class Gut(models.Model):
description = models.CharField(max_length=255, blank=True, null=True)
datetime = models.DateTimeField()
reaction_id = models.IntegerField()
class Meta:
db_table = 'gut'
class Meal(models.Model):
meal_type = models.CharField(max_length=255)
date = models.DateTimeField()
class Meta:
db_table = 'meal'
class MealFood(models.Model):
meal = models.OneToOneField(Meal, models.DO_NOTHING, primary_key=True)
food = models.ForeignKey(Food, models.DO_NOTHING)
class Meta:
db_table = 'meal_food'
unique_together = (('meal', 'food'),)
class Reaction(models.Model):
reaction = models.CharField(max_length=45)
class Meta:
db_table = 'reaction'
...\mysite\settings.py
from pathlib import Path
import pymysql
pymysql.install_as_MySQLdb()
...
INSTALLED_APPS = [
'diet.apps.DietConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'diet_py',
'USER': 'username',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
...
after model code finished. you need to run makemigrations command in CLI
python manage.py makemigrations
When you run this command you can see the modifications and additions that you are created in the command line some thing like following
diet/migrations/0001_initial.py
- Create model Food
if that not worked. The try the migrate command with app name as parameter like bellow
python manage.py makemigrations diet
Related
I can't find a solution for the following error:
RuntimeError: Model class users.models.User.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
The INSTALLED_APPS:
LOCAL_APPS = [
"api.users",
"api.achievements",
"api.others",
]
# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
Models folder
users/models/__init__.py:
from .User import * # noqa
from .Profile import * # noqa
users/models/User.py:
""" User related models """
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from django_countries.fields import CountryField
from api.others.constants import GENDER
class User(AbstractUser):
"""
Default custom user model for Dezumi API.
If adding fields that need to be filled at user signup,
check forms.SignupForm and forms.SocialSignupForms accordingly.
"""
birth_date = models.DateField(null=True, blank=True)
country = CountryField(null=True, blank=True, blank_label='Select country')
gender = models.CharField(choices=GENDER, max_length=6, null=True, blank=True)
is_verified = models.BooleanField(
default=False,
)
def get_absolute_url(self):
"""Get url for user's detail view.
Returns:
str: URL for user detail.
"""
return reverse("users:detail", kwargs={"username": self.username})
The app is on installed_apps, so what could it be? Something with the init.py?
Directory Structure:
api
├── api
│ ├── __init__.py
│ ├── conftest.py
│ ├── users
│ │ ├── admin
│ │ ├── api
│ │ │ ├── serializers.py
│ │ │ └── views.py
│ │ ├── migrations
│ │ ├── models
│ │ │ ├── __init__.py
│ │ │ ├── Profile.py
│ │ │ └── User.py
│ │ ├── __init__.py
│ │ ├── apps.py
│ │ └── ...
│ └── ...
├── config
│ ├── settings
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── local.py
│ │ ├── production.py
│ │ └── test.py
│ ├── __init__.py
│ └── ...
├── requirements
├── utility
├── manage.py
└── ...
Log:
File "path\api\api\users\admin\__init__.py", line 1, in <module>
from .Profile import * # noqa
File "path\api\api\users\admin\Profile.py", line 3, in <module>
from users.models.Profile import Profile
File "path\api\api\users\models\__init__.py", line 1, in <module>
from .User import * # noqa
File "path\api\api\users\models\User.py", line 11, in <module>
class User(AbstractUser):
File "path\lib\site-packages\django\db\models\base.py", line 113, in __new__
raise RuntimeError(
RuntimeError: Model class users.models.User.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
apps.py from users
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class UsersConfig(AppConfig):
name = "api.users"
verbose_name = _("Users")
def ready(self):
try:
import api.users.signals # noqa F401
except ImportError:
pass
Explicitly referencing the Users app configuration class might work:
LOCAL_APPS = [
"api.users.apps.UsersConfig",
...
]
I am trying to create an extended Custom User model that adds a level field of 0 to the User model which is not displayed on the form. But when I try to do this, I get the error no such table: users_customuser. I am new to Django. How can I implement what I described earlier and what I am doing wrong? Just in case I have done migrations...
Here is a structure of the project:
│ db.sqlite3
│ manage.py
│
├───ithogwarts
│ │ asgi.py
│ │ settings.py
│ │ urls.py
│ │ wsgi.py
│ │ __init__.py
│ │
│ └───__pycache__
│
├───main
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ │ __init__.py
│ │ │
│ │ └───__pycache__
│ │
│ ├───static
│ │ └───main
│ │ ├───css
│ │ │ footer.css
│ │ │ header.css
│ │ │ index.css
│ │ │
│ │ ├───img
│ │ │
│ │ └───js
│ │ script.js
│ │
│ ├───templates
│ │ └───main
│ │ index.html
│ │ layout.html
│ │ level_magic.html
│ │
│ └───__pycache__
│
├───templates
│ └───registration
└───users
│ admin.py
│ apps.py
│ forms.py
│ models.py
│ tests.py
│ urls.py
│ utils.py
│ views.py
│ __init__.py
│
├───migrations
│ │ 0001_initial.py
│ │ __init__.py
│ │
│ └───__pycache__
│
├───static
│ └───users
│ └───css
│ login.css
│ register.css
│
├───templates
│ └───users
│ login.html
│ register.html
│
└───__pycache__
models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
level = models.IntegerField(default=0)
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from .models import CustomUser
class RegisterUserForm(UserCreationForm):
username = forms.CharField(label="Имя", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input',
'placeholder': 'введите ваше имя'}))
email = forms.CharField(label="Почта", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-control',
'placeholder': 'введите вашу почту'}))
password1 = forms.CharField(label="Пароль", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input',
'placeholder': 'введите пароль'}))
password2 = forms.CharField(label="Подтверждение пароля", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input',
'placeholder': 'подтвердите ваш пароль'}))
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
for field_name in ['username', 'email', 'password1', 'password2']:
self.fields[field_name].help_text = None
class Meta:
model = CustomUser
fields = ('username', 'email', 'password1', 'password2')
views.py:
from django.contrib.auth import logout
from django.contrib.auth.views import LoginView
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import RegisterUserForm, LoginUserForm
class RegisterUser(CreateView):
form_class = RegisterUserForm
success_url = reverse_lazy('login')
template_name = 'users/register.html'
settings.py:
AUTH_USER_MODEL = 'users.CustomUser'
You have to make use of these two commands -
python manage.py makemigrations (It creates the migration)
python manage.py migrate (Actually creates the table in database)
Here is my project structure:
│ .gitignore
│ README.md
│ requirements.txt
│ start.py
│
├───app
│ │ main.py
│ │
│ ├───apis
│ │ └───v1
│ │ │ __init__.py
│ │ │
│ │ │
│ │ ├───routes
│ │ │ │ evaluation_essentials.py
│ │ │ │ training_essentials.py
│ │ │
│ │
│ ├───models
│ │ │ request_response_models.py
│ │ │ __init__.py
│ │ │
This is what the outermost, start.py looks like:
import uvicorn
if __name__ == "__main__":
from fastapi import Depends, FastAPI
from app.apis.v1 import training_essentials, evaluation_essentials
app = FastAPI(
title="Some ML-API",
version="0.1",
description="API Contract for Some ML API",
extra=some_important_variable
)
app.include_router(training_essentials.router)
app.include_router(evaluation_essentials.router)
uvicorn.run(app, host="0.0.0.0", port=60096)
And, all my endpoints and viewfunctions have been created in training_essentials.py and evaluation_essentials.py
for example, this is what training_essentials.py looks like:
from fastapi import APIRouter
from fastapi import FastAPI, HTTPException, Query, Path
from app.models import (
TrainingCommencement,
TrainingCommencementResponse,
)
router = APIRouter(
tags=["Training Essentials"],
)
#router.post("/startTraining", response_model=TrainingCommencementResponse)
async def start_training(request_body: TrainingCommencement):
logger.info("Starting the training process")
## HOW TO ACCESS APP HERE?
## I WANT TO DO SOMETHING LIKE:
## some_important_variable = app.extra
## OR SOMETHING LIKE
## title = app.title
return {
"status_url": "some-status-url",
}
How do I access APP properties, its variables inside that viewfunction in my endpoint?
You can access the request.app as
from fastapi import Request
#router.post("something")
def some_view_function(request: Request):
fast_api_app = request.app
return {"something": "foo"}
I have seen this tutorial https://samulinatri.com/blog/django-ckeditor-codesnippet-hightlightjs-youtube/ and I have downloaded the youtube plugin here https://ckeditor.com/cke4/addon/youtube
Then I created the youtube folder and pushed it into it. Specifically my_project / static / ckeditor / ckeditor / plugins / youtube /
After I python manage.py runserver, field ['content'] show normal, field ['content1'] it doesn't work (does not display frames textarea).
Someone helped me check, I did something wrong. Thanks !!!
File model.py
class Posts(models.Model):
title = models.CharField(max_length=50)
content = RichTextUploadingField(extra_plugins=['codesnippet'],)
content1 = RichTextUploadingField(
config_name='special',
extra_plugins=['youtube'],
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/youtube/',
'plugin.js',
)],
)
File setting.py
INSTALLED_APPS = [
'suit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'ckeditor',
'ckeditor_uploader',
]
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
},
'special': {
'toolbar': 'Special',
'toolbar_Special': [
['Bold'], ['CodeSnippet', 'Youtube'],
],
'extraPlugins': ','.join(['codesnippet', 'youtube']),
}
}
File urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include(('accounts.urls', 'accounts'), namespace='accounts')),
path('blog/', include(('blog.urls', 'blog'), namespace='blog')),
path('ckeditor/', include('ckeditor_uploader.urls')),
]
if settings.DEBUG:
import debug_toolbar
debug_patterns = [
re_path(r'^__debug__/', include(debug_toolbar.urls)),
]
urlpatterns = debug_patterns + urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My_project
├── blog <= This my_app
│ ├── view.py
│ ├── form.py
│ ├── model.py
├── project <= Project settings directory
│ ├── __init__.py
│ ├── settings.py <= settings
│ ├── urls.py
│ └── wsgi.py
├── static
│ ├── ckeditor
│ ├── ckeditor_uploader
│ ├── ckeditor
│ ├── plugins
│ └── youtube
│ └── youtube
│ └── images
│ └── lang
│ └── plugin.js
│ └── ....
│ └── ...
│ └── ...
In your models.py file, you need to point to the directory where the plugin.js is.
I believe the directory you should refer to is this:
class Posts(models.Model):
title = models.CharField(max_length=50)
content = RichTextUploadingField(extra_plugins=['codesnippet'],)
content1 = RichTextUploadingField(
config_name='special',
extra_plugins=['youtube'],
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/',
'plugin.js',
)],
)
I'm developing a django app. It has three apps in it, each with it's own template directory and index.html file. But when I call view from the second app it picks up the template file from the first app rather than the second one.
Is it a must that every template name be unique?
my projects directory:
├───jobs
│ ├───migrations
│ ├───static
│ └───templates
├───job_portal
├───main_app
│ ├───migrations
│ ├───static
│ └───templates
├───project_static
│ ├───css
│ ├───fonts
│ ├───images
│ └───js
└───recruiters
├───migrations
├───static
│ ├───css
│ ├───fonts
│ ├───images
│ └───js
└───templates
In Django you can use templates with the same names for different apps. But you should add subfolders inside app's template directory like this:
my_app/templates/my_app/base.html
second_app/templates/second_app/base.html
Now in views you should include app name to the template name:
return render(request, 'my_app/base.html')
return render(request, 'second_app/base.html').