Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Infinite Load Page Phenomenon in Django Virtual Environments
I'm using MAC, and I had a problem developing django using virtual environments. My development environment uses vscode to access the aws server, open the django virtual environment with 127.0.0.1:8000, and test the page using local(Mac) chrome. I didn't have any particular issues before, but recently, page loading has suddenly slowed down and the page loading bar is running at infinity. I changed the operating system to Windows and tried again, but there was no problem. The issue only happens on my MacBook. What should I do? I emptied my MacBook's Chrome cache and reinstalled Chrome, but nothing improved. I was wondering if it was a vscode problem, but my development environment is being developed using aws server, so it means that it is not a vscode problem to operate smoothly in Windows environment. -
Celery Beat cannot connect to Rabbitmq container
My celery beat docker container has (from what i believe) problems connecting the message broker. I have a RabbitMQ container running: .... rabbitmq: image: rabbitmq:3.11.13-management-alpine container_name: 'rabbitmq' ports: - 5672:5672 - 15672:15672 env_file: - .env volumes: - ./data:/var/lib/rabbitmq/mnesia networks: - rabbitmq_go_net .... And a Python container running a Django application with Celery (there are multiple more containers running the backend itself, celery workers, celery beat and celery flower, which all utilize the same backend files but handle different tasks): .... celery-beat: build: context: . dockerfile: ./compose/local/django/Dockerfile container_name: 'beat' image: beat command: ["./wait-for-it.sh", "0.0.0.0:1337", "--", "/start-celerybeat"] volumes: - .:/app env_file: - .env depends_on: - rabbitmq - backend restart: always .... Starting script for celery beat start.sh (executed by /start-celerybeat): #!/bin/bash set -o errexit set -o nounset rm -f './celerybeat.pid' celery -A app beat -l INFO app/celery.py: from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()#(lambda: settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): .... app/settings.py INSTALLED_APPS = [ .... 'django_celery_results', 'django_celery_beat', .... ] CELERY_BROKER_URL = CONFIG.get('CELERY_BROKER_URL') CELERY_RESULT_BACKEND = CONFIG.get('CELERY_RESULT_BACKEND') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" .env RABBITMQ_USER=user RABBITMQ_PASSWORD=password RABBITMQ_PORT=5672 RABBITMQ_HOST=rabbitmq CELERY_BROKER_URL=amqp://${RABBITMQ_USER}:${RABBITMQ_PASSWORD}@localhost:${RABBITMQ_PORT}/${RABBITMQ_HOST} CELERY_RESULT_BACKEND=amqp:// I receive the … -
Problem in creating folder and file after upload in Django
I'm creating a source code evaluater platform using React and Django. Basically an user is going to upload a source file of his choice, my frontend sends the file to backend, which is working fine, and my backend has to create a copy of the file in a specific folder structure, because the code evaluater (different application) is set to access this structure searching for new files. The folder structure is basically like this: I've a first folder name Delivereds, inside it I've many folders named by the user id, inside each of these folders I've many folders named by the submission id. To simplify this problem solving, let's deal with this ignoring user id, let's just focus on folder adress like this: "/Delivereds/Question1/code.c++". My problem is that when I try to create a folder, it doesn't work. I'm pretty much a beginner in Django, so I don't really know if I need to set some configs in the main settings file. The solutions that I found in my searches are really simple and didn't work in my case. My current code is like this: elif request.method == 'POST': if request.FILES.get('file'): file = request.FILES['file'] parent_dir = '..\Delivereds\Question1' path = os.path.join(parent_dir, … -
Better way to connect django model with django cms page/placeholder
I'm making a website, and one of the features - News. I have a model News with some fields, to have a better user experience i thought that i need some more information for every News - html snippet and for good administrating that additional content for News, i decided that i need to use django csm. So on every page i have an information from News model and in the end of that - html snippet made with cms. And there is a problem - i don't know the better way to make my wishes. Important bit: i want to make all connections with model slug. I read docs about apphooks - but maybe it's not a good approach in my case? Couse apphooks make application embedding to django cms, but i need only the piece of creation and connecting of html template made by this cms. Additionally i tried just take a Page made by cms and put it in my html, but it was something wrong there, maybe it is not possible? Maybe i can see pages only on cms urls? page = Page.objects.all()[0] # for example in views I tried to make the model placeholder, but … -
Django- admin installation error - Failed building wheel for screen
I published my project on Windows server, but domain.com/admin is not working. As a result of research on the internet, I wanted to install Django-admin, but I am getting an error. I didn't have such a problem on my computer. Creating library build\temp.win-amd64-cpython-312\Release\source\str_util.cp312-win_amd64.lib and object build\temp.win-amd64-cpython-312\Release\source\str_util.cp312-win_amd64.exp str_util.obj : error LNK2001: unresolved external symbol PyUnicode_AS_UNICODE build\lib.win-amd64-cpython-312\screen\str_util.cp312-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.38.33130\\bin\\HostX86\\x64\\link.exe' failed with exit code 1120 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for screen Failed to build screen ERROR: Could not build wheels for screen, which is required to install pyproject.toml- based projects C:\inetpub\vhosts\domain.com.tr\httpdocs> Urls.py from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
why do i get this error "cannot unpack non-iterable bool object"
i get this error "cannot unpack non-iterable bool object" as i try to get user input from a form in django which in this case is an email def send_email(request): recepient_list=[] if request.method == "POST": email = request.POST['pwd_email'] print(email) if User.objects.filter(email == email).exists: recepient_list.append(email) send_mail("PASSWORD RESET", f"Your password resetkey is {random_no} \n Do not share this key with anyone", "eliaakjtrnq@gmail.com",recepient_list,fail_silently=False,) recepient_list.clear() -
Converting Flask or Django Web App to Desktop App for Secure Distribution
I have developed a web application using Flask/Django, and now I'm interested in converting it into a desktop application. I want users to be able to run the application directly from their desktop without needing a web browser, and I'm particularly interested in distributing it securely without exposing the source code. Can someone guide me on how to achieve this conversion? Are there any tools or frameworks available that can help in this process? I'm aiming to preserve the functionality and user experience of my web application while making it suitable for desktop usage and secure distribution. Additionally, I would appreciate any insights or best practices from those who have successfully converted web apps to desktop apps before and managed to distribute them securely without exposing the source code. Thank you in advance for your help! -
JWT refresh token is in httponly cookie, How to use DRF simple-jwt to regen the token
I have a front and backend app, front is react and backend is python Django (DRF), so my problem is I store the refresh token inside an HttpOnly cookie and send it in every request, but the DRF endpoint for refresh token (rest_framework_simplejwt.views.TokenRefreshView) will read the token itself from request.data which is the body of the Http request, is there a better way to handle this view other than rewriting a custom view? -
Django/ Office 365 : 535, b"5.7.139 Authentication unsuccessful, user is locked by your organization's security defaults policy
Running into the following error when trying to send email with Django: 535, b"5.7.139 Authentication unsuccessful, user is locked by your organization's security defaults policy. Here is my current config: #Emailing Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_FROM = 'email@email.com' EMAIL_HOST_USER = 'email@email.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS= True This error was raised here: https://learn.microsoft.com/en-us/answers/questions/1469524/error-when-testing-smtp-for-django-website The irony of the answer provided by Microsoft is to suggest to disable the security default and also adding "not recommend". It seems the error is specific to Microsoft and comes from the use of SMTP, which MS's security doesnt like and encourage the use of OAuth. Can someone suggest an approach that worked for them? Did you disable the security defaults (for the specific email): is it risky? Did you implement OAuth and if so what steps did you take? -
I am hosting django project on hostinger using vps
I am trying to host my Django project on hostinger, I am using gunicorn to connect to vps and Nginx as the web server I correctly configured Nginx and gunicorn , everything is working without logs,But my site is not showing in the IP adress. -
Django IIS Deployment - HTTP Error 404.0 - Not Found
I need explanation on how to deploy Django Application on Windows IIS Server. I am struggling to follow the following tutorial I have a project which looks like this : [My_App] --> [My_App_Venv] --> [abcd] |-> manage.py |-> [abcd] |-> settings.py |-> [static] |-> ... [ example ] is used to represent folders I Need to understand how I should setup my IIS website : What should be FastCGI Application settings Full Path : C:\xxxxx\My_App\My_App_Venv\Scripts\python.exe Arguments : C:\xxxxx\My_App\My_App_Venv\Lib\site-packages\wfastcgi.py Environment Variables : 1. DJANGO_SETTINGS_MODULE : abcd.settings (I think this is ok) 2. PYTHONPATH : C:\xxxxx\My_App (I am not sure about this) 3. WSGI_HANDLER : abcd.wsgi.application (I think this is ok) Create and Configure a New IIS Web Site what should be the physical Path ? C:\xxxxx\My_App ? C:\xxxxx\My_App\abcd ? C:\xxxxx\My_App\abcd\abcd ? Configure the mapping module ## (which i assume is correct) Request path: * Module: FastCgiModule Executable : C:\xxxxx\My_App\My_App_Venv\Scripts\python.exe|C:\xxxxx\My_App\My_App_Venv\Lib\site-packages\wfastcgi.py Name : Django Handler output Hope someone can help to understand what I am doing wrong, I might use wrong path somewhere. Note : When I do By hand : cd C:/xxxxx/My_App/My_App_Venv .\\scripts\Activate cd.. cd abcd python manage.py runserver The website is well displayed on : http://127.0.0.1:8000/ -
jQuery loading animation not showing
I am attempting to follow the answer here to create a loading animation using jQuery: https://stackoverflow.com/a/1964871/23334971 Unfortunately, no loading animation shows for me and I'm not sure why. I am using Python/django for my server-side script. I'm not sure how to produce a minimal working example because the server side code takes a good few seconds to run. Maybe just replace it with a delay? I'm a complete noob so there's probably something obvious wrong with my code: This is my HTML: {% load static %} <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="{% static 'calculator/script.js' %}"></script> <link rel="stylesheet" href="{% static 'stylesheet.css' %}"> </head> <body> <article> <form id="calculatorForm"> <label for="num1">Numbers</label> <input type="number" name="number1" id="number1"> <input type="number" name="number2" id="number2"><br /> <button type="submit" role="button">Calculate</button><br /><br /> </form> <div class="modal"></div> <div id="result"></div> </article> </body> </html> stylesheet.css: (just copied and pasted from the linked stackoverflow answer) .modal { display: none; position: fixed; z-index: 1000; top: 0; left: 0; height: 100%; width: 100%; background: rgba( 255, 255, 255, .8 ) url('https://i.stack.imgur.com/FhHRx.gif') 50% 50% no-repeat; } /* When the body has the loading class, we turn the scrollbar off with overflow:hidden */ body.loading .modal { overflow: hidden; } /* Anytime the body has the loading class, … -
how to present in Jinja2 notation groupedby dataframe to html template in Django
In Django view I have function where I got dataframe from QuerySet. def owner_observation_count(request): form = ReportForm(request.GET) context = {} if form.is_valid(): organisation = form.cleaned_data['organisation'] department_for_report = form.cleaned_data['department_for_report'] employee_total = Observation.objects.values('owner__last_name','owner__first_name', 'date_created__year','date_created__month').annotate(owner_count_2=Count('owner_id')) if organisation: employee_total = employee_total.filter(users_organization=organisation) if department_for_report: employee_total = employee_total.filter(users_department=department_for_report) employee_total_pd = pd.DataFrame.from_dict(employee_total) employee_total_pd["Emploeey"] = employee_total_pd["owner__last_name"].str.cat(' ' + employee_total_pd["owner__first_name"].str.get(0) + '.') employee_total_pd = employee_total_pd.drop('owner__last_name', axis=1) employee_total_pd = employee_total_pd.drop('owner__first_name', axis=1) emp_columns = {'date_created__year': 'Year', 'date_created__month': 'Month', 'owner_count_2': 'Qty'} employee_total_pd.rename(columns=emp_columns, inplace=True) which gives the result | Year | Month | Qty | Employee | |------|-------|-----|------------| | 2023 | 6 | 2 |Kefer A. | | 2023 | 9 | 1 |Napylov S. | | 2023 | 6 | 2 |Grosheva N. | | 2023 | 9 | 3 |Sapego G. | | 2023 | 8 | 3 |Danilin S. | | 2023 | 8 | 2 |Alekseeva L.| | 2023 | 8 | 2 |Smirnova E. | | 2023 | 7 | 1 |SHaripov R. | | 2023 | 9 | 14 |Lyalina L. | | 2024 | 8 | 2 |Husainov S. | | 2024 | 8 | 3 |Kachanova T.| | 2024 | 8 | 6 |Chistova V. | | 2024 | 6 | 1 |Vishnyakov M| | … -
Cant pass data to Chart.js with Django
Im using bootstrap template for my website and have problem to pass data from view in django to html to chart.js I tried to pass data like any other variable but it didnt worked. I cant see data I have 2 charts one (pie) with predefined data set and second (doughnut) i want to pass data from view, neither shows after render. What do i do wrong? View.py ctx = { "tournament": tournament, "pairing": pairing, "players_points": players_points, "army_points": army_points, "teamB": teamB, "form": form, "green": green, "yellow": yellow, "red": red, "green_p": green_p, "yellow_p": yellow_p, "red_p": red_p, "total": total, # "chart_data": chart_data, "chart_data": json.dumps(chart_data), } return render(request, "pairing5v5.html", ctx) html <div class="container-fluid pt-4 px-4"> <div class="row g-4"> <div class="col-sm-12 col-xl-6"> <div class="bg-secondary rounded h-100 p-4"> <h6 class="mb-4">Pie Chart</h6> <canvas id="pie-chart" width="500" height="500"></canvas> </div> </div> <div class="col-sm-12 col-xl-6"> <div class="bg-secondary rounded h-100 p-4"> <h6 class="mb-4">Doughnut Chart - {{ chart_data|safe }}</h6> <canvas id="doughnut-chart"></canvas> </div> </div> </div> </div> main.js // Pie Chart var ctx5 = $("#pie-chart").get(0).getContext("2d"); var myChart5 = new Chart(ctx5, { type: "pie", data: { labels: ["Italy", "France", "Spain", "USA", "Argentina"], datasets: [{ backgroundColor: [ "rgba(235, 22, 22, .7)", "rgba(235, 22, 22, .6)", "rgba(235, 22, 22, .5)", "rgba(235, 22, 22, .4)", "rgba(235, 22, 22, … -
Django (removal of .auth and .django tables that are created after migrate command)
I have these 10 tables in Django (6-Auth tables and 4 Django tables) I am not using these files in my production project, I thought of removing them but read that its not a good practice to remove. I am dealing with some million records(GET and POST operations), Will these tables effect my code performance in the long run? I have Tried removing these tables but all of them are interlinked with foreign keys. -
Is this proper way to handle all CRUD operations in a single view (endpoint) using HTMX?
I'm new to using HTMX with Django and I'm seeking guidance. I'm in the process of redesigning a large CRUD application, aiming to integrate HTMX for improved interactions. Given the complexity of the app and its interactions with the database across various models, I want to ensure I start off on the right foot by adopting HTMX best practices early on. I've seen in many tutorials that everyone follows the common practice of creating separate views and URL paths for each database transaction (such as create, edit, delete, update). As I think that this could result in a significant amount of additional code and time investment, I would prefer to put all of the application logic in just one view (or endpoint), for each model. Can you please suggest me if this is the right flow and right way to do it: def movie(request, template_name="movies.html"): movies = Movie.objects.all() movie_form = MovieForm(request.POST or None) if request.method == 'POST': action = request.POST.get('action') # 1) CREATE if action == 'add_movie': if movie_form.is_valid(): movie_form.save() content = render(request, 'partials/movie-table.html', {'movies': movies}) return HttpResponse(content, status=201, headers={ 'HX-Trigger': json.dumps({'create': movie_form.cleaned_data['name']})} ) else: content = render(request, 'error.html', {'error': movie_form.errors}) return HttpResponse(content, status=202) # 2) DELETE elif action == … -
Django Rest Framework basic set of APIs around authentication
I'm a django newby and I'm looking to expose basic services like: forgotten password, password change. I would expect to have those services for free but looking here and there it looks like we have to do them by hand, is that correct? Is there any explanation for that? -
I have been trying to runserver for my code but I keep getting this error
your text I'm trying to create a website using django but each time I runserver i keep getting this error message: TemplateDoesNotExist at / base.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 5.0.2 Exception Type: TemplateDoesNotExist Exception Value: base.html Exception Location: C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages\django\template\backends\django.py, line 84, in reraise Raised during: main.views.home Python Executable: C:\Users\Admin\KredibleConstructionWebsite\venv\Scripts\python.exe Python Version: 3.10.11 Python Path: ['C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\python310.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\Admin\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0', 'C:\Users\Admin\KredibleConstructionWebsite\venv', 'C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages'] Server time: Tue, 20 Feb 2024 09:17:47 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction\main\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages\django\contrib\admin\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages\django\contrib\auth\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction\main\templates\base.html (Source does not exist) Error during template rendering In template C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction\main\templates\main\home.html, error at line 3 your text what can I do to resolve this cos I have corrected the base.html file mutliple times and even changed the directory to templates\main\bas.html but it is not working -
POST http://localhost:8000/login/ 401 (Unauthorized)
I'm working on a React Typescript and Django application, but can't get the authification to work. I have spent hour upon hours on it, but can't fin a solution. Any help would be much appriciated. App.tsx import { useEffect, useState } from "react"; import { Home } from "./Home"; import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import { Login } from "./Login"; import Navbar from "./components/Navbar"; import axios from "axios"; export interface Movie { id: number; title: string; genre: string; year: number; } function App() { const [movies, setMovies] = useState<Movie[]>([]); const getMovies = async (): Promise<Movie[]> => { try{ const { data } = await axios.get<Movie[]>('http://localhost:8000/api/movies') setMovies(data) console.log(data) return data }catch (error){ console.error("error",error); return [] } } useEffect(() => { getMovies(); },[]) return ( <main className="bg-slate-500 p-60 min-h-screen"> <Router> <Navbar /> <Routes> <Route path="/login" element={<Login />} /> <Route path="/" element={<Home movies={movies} />} /> </Routes> </Router> </main> ) } export default App; Login.tsx import axios, { AxiosResponse } from "axios"; interface User { email: string; password: string; } async function logIn(e: React.FormEvent<HTMLFormElement>) { e.preventDefault(); console.log("Logging in"); try { const user: User = { email: "e@a.com", password: "hei" } const response: AxiosResponse = await axios.post('http://localhost:8000/login/', user, { withCredentials: … -
Python extension in VSCode cannot see virtual python
I working on a Django project. The problem I have is in the screenshot below: could not resolved from source I used "python3 -m venv env" to setup the virtual environment. I also installed Django with the "env" activated. Pip freeze confirms the installation: requirements VSCode cannot see virtual python Below is what I tried to fix this: Reinstalled VSCode Reinstalled the Python extension Manually selected the interpretor with the path "env/bin/python" using "Enter interpretor path..." The problems will not resolve. I've tried other questions that suggest to simply select to the right interpretor in the virtual environment folder. Didn't work. I noticed, when I created a virtual environment and activated it from the terminal in VSCode, VSCode did not automatically trigger the suggestion to use it. It's as if VSCode cannot see it at all. The packages in virtual environment clearly show Django was installed: Django installed Strangely, the same problem shows in Pycharm too. -
pyodbc, mssql-django Referencing row values by names in Django
In a test script, I can reference row values by name and the returned row type is "<class 'pyodbc.Row'>" import pyodbc SERVER = '' DATABASE = '' USERNAME = '' PASSWORD = '' connectionString = f'DRIVER={{ODBC Driver 18 for SQL Server}};SERVER={SERVER};DATABASE={DATABASE};UID={USERNAME};PWD={PASSWORD}' connection = pyodbc.connect(connectionString) SQL_QUERY = "SELECT * FROM fund_performance" cursor = connection.cursor() cursor.execute(SQL_QUERY) records = cursor.fetchall() for r in records: print(type(r)) print(f"{r.fund}\t{r.nav}") However when I try the same code in a Django app, the row type is a tuple, and therefore I cannot reference the values by name. I am using mssql-django to connect, and same virtual environment for both and this is my django db config: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'name', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': 'db.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 18 for SQL Server', }, }, } Is there a connection config that forces it to return a row object? or is there another way to return objects not tuples. -
Implementing Multiple Login/Signup Systems in Django for Different User Types
I'm working on a Django project (Food delivery app) where I need to implement multiple login/signup systems for three types of users (in single project): customers, sellers, and drivers. Each user type has its own set of models, such as Customer, Seller, Driver, along with related meta models like Seller Group / permissions / roles etc. Additionally, there are separate permission systems for each type. My goal is to have different login/signup methods for each user type. For example: Customers log in/sign up using mobile OTP. Sellers log in/sign up using a business email and password. I've organized my project into separate apps for each user type (customers, sellers, drivers), and I have custom user models.py defined in each app (AbstractUser, UserManager, PermissionMixins etc). But as per my knowledge, while using custom auth, I have to define AUTH_USER_MODEL in settings.py. where I can mention only one model. How can I implement these different login/signup methods and ensure that the authentication and authorization processes are tailored to each user type? Are there Django packages or best practices for handling such scenarios? Any guidance, code examples, or recommended resources would be greatly appreciated. Thanks in advance! -
How to use multiple database with Django and SQLAlchemy
Description: I have a Django application that currently stores data for multiple brands in a single database. Each brand's data, including user details and relevant information, is stored in separate tables within this database. However, I now have a requirement to migrate the application to use separate databases for each brand. Current Setup: One database containing tables for multiple brands. User details and relevant data for each brand stored in separate tables within this database. Desired Setup: Separate databases for each brand. User details and relevant data for each brand stored in their respective databases. Tools Used: Django for web framework. SQLAlchemy for database ORM. Alembic for database migrations. Key Questions: How can I configure Django to use separate databases for each brand? What changes do I need to make to SQLAlchemy models to support this new database structure? How should I handle database migrations using Alembic to ensure seamless transition to the new setup? Are there any best practices or potential pitfalls I should be aware of during this migration process? Currently, I'm following the simple technique to connect the single Database. engine = create_engine(<Database URL>) session = scoped_session(sessionmaker(bind=engine, autocommit=True)) Base.metadata.create_all(engine) Any guidance, examples, or resources would be greatly … -
Django translation issue for Marathi language
I have to translate the string in django, for table pagination “0 of %(cnt)s selected” in Marathi language . I am switch but when I am selected the thing from table it will automatically change into english. This not happen for hindi translation, Hindi translation works but the for the Marathi translation it's automatically change into english language how can solve this issue. I have taken this msgid from django admin locale file. When I am select anything from the table the pagination “0 of %(cnt)s selected” is in Marathi language. If I am selected anything from table it will not change automatically into english language. -
Error when removing/unregistering Groups: "django.contrib.admin.sites.NotRegistered: The model Group is not registered"
Note: I'm posting this question for completeness/more documentation. The error itself does not have a specific question asked about it, but there are answers if you look just one step further for it: Answer 1 & Answer 2. However, the answers are lacking depth so I'm hoping to provide some additional value by answering this question with more depth. If not appropriate, please feel free to comment and I'll remove. Context: I already had written some Django code for an app I'm building, but decided to follow this tutorial along and when I was trying to remove the Groups table from the Admin page, I stumbled upon this error: django.contrib.admin.sites.NotRegistered: The model Group is not registered and an initial Google search did not help quite well, but a search in SO's Django tag page lead me to this answer and everything was solved. I tried creating a new Django project and replicating the steps of the tutorial above but still got the same error.