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)
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",
...
]
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"}
Completely new to Django. I'm building a website where users can make profiles, search for other profiles, and view basic information.
I'm unsure about how to organize the apps. I want to following things on the navigation bar:
"About Us", "How it Works", "Join", "Login"
I know that users (join + login) will be its own app, but how would I bundle all of the information that will show up on the navigation bar? Will that just be one main app because it doesn't really do anything complex and really just presents text?
The concept of app in Django is that it does thing. For example if you are creating a website for school you have students as an app which manages students, an app for exams which only manages exams, grades etc. So your app should typically do one thing, if it does not break it down. The whole idea behind Django is having modular components which can act on their own.
In your case, what I would do is create an app called userapp. In userapp, I will have profile as a model containing username, password, fname, lname, picture, dob, hobbies etc.
On your home page, you can have separate flatpages for about us, how it works. These do not have to be app.
My project structure
├───.idea
├───firstapp
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───myproj
│ └───__pycache__
├───secondapp
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───static
│ ├───admin
│ │ ├───css
│ │ ├───fonts
│ │ ├───img
│ │ │ └───gis
│ │ └───js
│ │ ├───admin
│ │ └───vendor
│ │ ├───jquery
│ │ └───xregexp
│ ├───css
│ ├───fonts
│ ├───img
│ └───js
└───templates
└───firstapp
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').
This is my structure. I have problem about implementing flask large application.
├─flasky
│ ├─app/
│ │ ├─templates/
│ │ ├─static/
│ │ ├─main/
│ │ │ ├─__init__.py
│ │ │ ├─errors.py
│ │ │ ├─forms.py
│ │ │ └─views.py
│ │ ├─__init__.py
│ │ ├─email.py
│ │ └─models.py
│ ├─migrations/
│ ├─tests/
│ │ ├─__init__.py
│ │ └─test*.py
│ ├─venv/
│ ├─requirements.txt
│ ├─config.py
│ └─manage.py
...
I encountered some problem When I was coding in email.py.
def send_email(to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
with the_app.app_context():
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
I don't know how to call modules to implement the_app.app_context(). I hope that it can direct send_email function to get app/templates of location to be successful.
I found what the problem was. I needed to define a flask app in email.py:
import os
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
the_app = Flask(__name__, template_folder=tmpl_dir)
I encountered a new problem with werkzeug.routing.BuildError, and I am searching for a solution. I found "Flask error: werkzeug.routing.BuildError" mentioned my problem.
werkzeug.routing.BuildError
BuildError: ('index', {}, None)
Because views.py had a typo arg of url_for(), I should type 'main.index'. It's right.
#main.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
...
return redirect(url_for('main.index'))
return render_template('index.html',
form=form, name=session.get('name'),
known=session.get('known', False),
current_time=datetime.utcnow())
But it can't enable the feature of sending email. I found "Python Flask Email KeyError KeyError: 'mail'" mentioned my problem. I needed to downgrade to flask_mail==0.9.0, which solved the problems.