Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Social sign in Django rest framework
For a flutter app, I need to develop some API using Django rest-framework. For the authentication what I have done so far, using simple token auth. When a new user sign-up and then verify his email, I generate a token and that token is then used to send requests. For logout, the token that is generated before needs to be deleted from the front end and redirected to the login page. If the user wants to log in again, the user needs to provide the email and the password. If the credentials are correct, the token is sent again. Now I have to implement Google sign-in. I am confused about the workflow. Can anyone guide me on how to do this same thing? Thanks in advance. -
Django on kubernetes pod no space left on device
So I am running Django App in kubernetes pod at when trying to save an image file: img_obj.image.save(img_file, File(img_file_org)) I am getting no space left error: File "/code/ocr_client/management/commands/pdf_to_image.py", line 126, in handle img_obj.image.save(img_file, File(img_file_org)) File "/opt/conda/lib/python3.7/site-packages/django/db/models/fields/files.py", line 88, in save self.name = self.storage.save(name, content, max_length=self.field.max_length) File "/opt/conda/lib/python3.7/site-packages/django/core/files/storage.py", line 54, in save return self._save(name, content) File "/opt/conda/lib/python3.7/site-packages/django/core/files/storage.py", line 274, in _save fd = os.open(full_path, self.OS_OPEN_FLAGS, 0o666) OSError: [Errno 28] No space left on device: '/code/pca_back_data/media/file1.png' I already ran kubectl exec <my-pod> -- df -ah And there is still 20% of the space left (100GB) I also ran as suggested in other thread: kubectl exec <my-pod> -- df -hi and the usage of inodes was only 5% I am not sure what else might be the issue here? Is there some config in Kubernetes that restricts usage of storage for a pod/process? -
django logging config with gunicorn and command line scripts
Up until now this config LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', } }, 'formatters': { 'verbose': { 'format': '%(asctime)s [%(levelname)s] %(name)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'INFO', }, }, } was good enough for me, everything to console then using PYTHONUNBUFFERED=TRUE and gunicorn config bind = "0.0.0.0:50000" workers = 1 worker_class = "gthread" threads = 2 worker_connections = 1000 timeout = 60 keepalive = 5 accesslog = "/var/log/gunicorn/myapp.com-access.log" errorlog = "/var/log/gunicorn/myapp.com-error.log" loglevel = "debug" capture_output = True everything went to accesslog or errorLog. Now that I need to use poetry run python manage.py sqlflush I run into trouble. all my logger.info() logs are also output to console so I get Logging in Logged in Logging in Already logged in BEGIN; SET FOREIGN_KEY_CHECKS = 0; TRUNCATE `myapp_imagemodel`; TRUNCATE `auth_user_groups`; TRUNCATE `auth_user_user_permissions`; TRUNCATE `auth_permission`; TRUNCATE `auth_group_permissions`; TRUNCATE `auth_user`; TRUNCATE `auth_group`; TRUNCATE `django_content_type`; TRUNCATE `myapp_game`; TRUNCATE `myapp_game_screenshots`; TRUNCATE `django_session`; TRUNCATE `django_admin_log`; SET FOREIGN_KEY_CHECKS = 1; COMMIT; How should I configure logging so it doesn't mess up with manage.py script's output? Can I still have it all in one file? -
Python 3.8 running on 64bit Amazon Linux 2/3.5.3 error: ctypes.util.find_library() did not manage to locate a library called 'pango-1.0-0'
I am trying to deploy an app on elastic beanstalk Python 3.8 running on 64bit Amazon Linux 2/3.5.3 server. I have weasyprint and GTK3 installed in my pc. Also 'C:\Program Files\GTK3-Runtime Win64\bin' exists in system environment variables. When I create an environment on elastic beanstalk using: eb create django-env I get an error: OSError: cannot load library 'pango-1.0-0': pango-1.0-0: cannot open shared object file: No such file or directory. Additionally, ctypes.util.find_library() did not manage to locate a library called 'pango-1.0-0' WeasyPrint is running fine on my windows system. But after environment creation on aws elastic beanstalk, I get the error in logs. I already checked here, but its not of much help to windows users -
Java FeignClient REST call to Django webserver throwing SocketTimeoutException
I have two micro services running, one in java tomcat and another in python Django. Java app calls python server using feignclient library. Some times calls are failed due SocketTimeoutException. At that specific time there is no load observed in python server. Ideally python API response in 100ms and we set a timeout of 1sec for feignclient with 2 retries. Please let me know how to handle this situation. -
Splitting admin.py in Django
I'm working on a Django project and have organized my admin-related code in the following file structure: myapp/ admin/ __init__.py common.py admin_a.py admin_b.py In the __init__.py file of the admin package, I'm currently using from .common import *, from .admin_a import *, and from .admin_b import * to import all names defined in the respective files. In a similar fashion, I have a file structure for the filters: myapp/ folder_a/ admin.py folder_b/ admin.py admin.py In the admin.py file at the top level, I'm using from folder_a.admin import * and from folder_b.admin import * to import all names defined in the respective files. My question is: What is the recommended way to split the admin.py file? Should I continue to use import * in the __init__.py and admin.py files, or is there a better approach? I'm concerned about potential namespace pollution, conflicts, and readability issues that may arise from using import *. I want to follow best practices and ensure a clean and maintainable codebase. Any advice or suggestions on the preferred approach for splitting the admin.py file in Django projects would be greatly appreciated. Thank you! -
Page not found (404) Battery not found
the error i am getting this is what the battery_registration_success page looks like I cant get my web application to generate static qr codes. I am building a django web application. My project is "Fake phone battery identification using blockchain technology". The user must enter the phone battery's details to register it in the system. Once successfully registered, the user will be given a unique battery id and a link to generate the qr code. When i click the link i get this error: 2023-06-28 14:08:17 [WARNING] django.request: Not Found: /fontriden/fontriden/qr_code/c549194f808cf837a9595b94b6eba295b902024bfa859f61ae72d589ce6eca59/ [28/Jun/2023 14:08:17] "GET /fontriden/fontriden/qr_code/c549194f808cf837a9595b94b6eba295b902024bfa859f61ae72d589ce6eca59/ HTTP/1.1" 404 5475 this is what my views.py looks like: def battery_registration_success(request): w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:7545")) contract = w3.eth.contract(address=CONTRACT_ADDRESS, abi=contract_abi) battery_id = request.session.get('battery_id') numeric_battery_id = int(battery_id, 16) # Convert hexadecimal string to integer qr_code_url = reverse('qr_code_image', args=(battery_id,)) battery_details = get_battery_details(w3, contract, battery_id) context = { 'battery_details': { 'battery_id': battery_id, 'product_name': battery_details[0], 'certification_mark': battery_details[1], 'serial_number': battery_details[2], 'watt_hours': battery_details[3], 'qr_code_url': qr_code_url, def qr_code_image(request, battery_id): try: battery = Battery.objects.get(id=str(battery_id)) except Battery.DoesNotExist: raise Http404("Battery not found") qr_image = generate_qr_code(battery) qr_image_data = qr_image.getvalue() battery_details = get_battery_details(battery_id) qr_code_filepath = generate_qr_code(battery, battery_details) context = { 'battery_details': { 'battery_id': battery.battery_id, 'product_name': battery_details[0], 'certification_mark': battery_details[1], 'serial_number': battery_details[2], 'watt_hours': battery_details[3], 'qr_code_filepath': qr_code_filepath, } } return render(request, … -
Django Bleach with CKeditor?
Good morning, have you already configured Django Bleach for CKEDITOR? Actually I'm using a form with Django. And I use CKEDITOR to be able to write. But is there a configuration to use Django Bleach with? Because in my template I use |safe. THANKS I want to safe the data send with ckeditor. models.py class Comment(models.Model): content = RichTextField(verbose_name="Message") forms.py class IdeaCommentForm(forms.ModelForm): captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) class Meta: model = Comment fields = ["content"] views.py if request.method == "POST": form = IdeaCommentForm(request.POST) if form.is_valid(): form.instance.user = user form.instance.idea = idea form.save() return redirect(idea) else: form = IdeaCommentForm() hrml <div class="card-body"> <p class="card-text">{{ comment.content|safe }}</p> </div> thks ! -
Proof Key for Code Exchange Error in Microsoft Active Directory
AADSTS9002325: Proof Key for Code Exchange is required for cross-origin authorization code redemption. I have followed this https://learn.microsoft.com/en-us/training/modules/msid-django-web-app-sign-in/1-introduction and got Proof Key for Code Exchange is required for cross-origin authorization code redemption . -
Django - asgi - uvicorn - multithreading
I was trying to find out benefits and shortcomings of using asgi instead of wsgi server with async and sync view when i found that asgi was creating multiple threads for multiple requests. I set up a demo project with 2 views (1 synchronous and 1 asynchronous with time.sleep and asyncio.sleep respectively). Using asgi when i make 500 simultaneous requests for synchronous view it make 500 threads (one for each request which is kind of counter intuitive because i was expecting a single thread to resolve 500 requests 1 by one), and when i make 500 simultaneous request for async view it is still creating 500 threads although when i log the thread id in async view, all requests are being handled by a single thread. I am not using any middleware or extra app that may have any synchronous code to cause this issue. More over i tried unicorn with FASTapi and it worked as expected (a single thread for async code). -
issues with using django inside vagrant
So this was my first time working with vagrant and django and i was following a course where he taught how to make vagrant file and run the virtual machine and inside how to make python virtual environment (named env). Then he taught how to initialize django and everything was working good so far, then using python manage.py runserver 0.0.0.0:8000 i ran the django server and it seemed to work on my chrome, i was seeing that rocket thing with django. The issue arised when i wanted to stop the server. He said to press ctrl+c to exit the server. When i pressed ctrl+c it stopped my vagrant and took me back to the termial (git bash) keeping the vm running in the background. When i tried closing the git bash it told me that vagrant was running do you still want to close it. Even after closing the terminal the server was still running. Does anyone know the way to close the server the correct way as i had to force kill to stop the server using the following commands ps aux | grep runserver and then using this command to kill the runserver kill -9 <PID> Does anyone … -
Apache WSGI IPC
I have a Django app running behind an Apache/ModWSGI server with multiple processes. I'd like to implement a feature where settings, such as model field labels, are stored in the database and dynamically updated in the UI. To avoid this from slowing down each Django request, I don't want to pull all model field names from the database in each request. I just want to pull them from the Django instance first loads, and then update them once if they're changed. It's pretty trivial to create a Django signal to hook onto my field name model, and dynamically update the field's "verbose name" value in memory. However, that only updates the process for that request. The other N-1 processes being run by Apache will still be using the old value. How would I tell the other processes to update a specific setting? Ideally, I want a very light-weight interprocess communication method to push a "field name changed" event to the other processes, which they would then consume and do that lightweight task of updating the value in their memory. There are a ton of multiprocessing tools for Python, but are there any specific ones for a task like this, especially … -
wagtail cms with codered extension how to add a form on the home page
I have content on my homepage using the styles and all available by the coderedcms extension of wagtail I am wondering how can I add a subscribe form for newsletters using the mail chimp integration. here is the refrence link to the extension. https://github.com/coderedcorp/coderedcms -
Django Custom authentication failing to keep user authenticated across requests
I have a custom model that I'm using together with a custom authentication backend: model class Radcheck(AbstractBaseUser, PermissionsMixin): class Operator(models.TextChoices): EQUAL = ':=', ':=' EQUALS = '==', '==' NOT_EQUAL = '!=', '!=' # id = models.BigAutoField(primary_key=True) username = models.TextField(default='') attribute = models.TextField(default='') op = EnumField(Operator, default=Operator.EQUAL) value = models.TextField(default='') package = models.ForeignKey(InternetPackage, on_delete=models.CASCADE, null=True) voucher_status = models.CharField(max_length=2, choices=expiry_choices, default='0') # last_login = models.DateTimeField(null=True) is_active = models.BooleanField(default=True) objects = RadcheckUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] groups = models.ManyToManyField( 'auth.Group', verbose_name='groups', blank=True, related_name='radcheck_users' # Specify a unique related_name for groups ) user_permissions = models.ManyToManyField( 'auth.Permission', verbose_name='user permissions', blank=True, related_name='radcheck_users' # Specify a unique related_name for user_permissions ) class Meta: db_table = 'radcheck' indexes = [ models.Index(fields=['username', 'attribute']), # Use this index if you use case insensitive queries # models.Index(fields=[models.functions.Lower('UserName'), 'Attribute']), ] def __str__(self): return self.username backend class RadiusBackend(BaseBackend): def authenticate(self, request, voucher=None, **kwargs): if request.path.startswith('/admin/'): return None # Return None for admin site requests auth_request = client.CreateAuthPacket( code=pyrad.packet.AccessRequest, User_Name=voucher, NAS_Identifier="Mikrotik" ) auth_request["User-Password"] = auth_request.PwCrypt(voucher) # Send request response = client.SendPacket(auth_request) if response.code == pyrad.packet.AccessAccept: # Authentication successful try: user = Radcheck.objects.get(username=voucher) # if user.is_active: print("------------------------------Done here with AUTH!----------------------------------------") return user except Radcheck.DoesNotExist: # User does not exist, handle accordingly print("----------------Voucher does … -
How to call API view from another View in Django REST framework?
I am trying to call APIView from another APIView, the code similar to: A.views.py from rest_framework import views from rest_framework.response import Response class A(views.APIView): def post(self, request, *args, **kwargs): return Response({"message": "class A"}) B.views.py from rest_framework import views from rest_framework.response import Response from A.views import A class B(views.APIView): def post(self, request, *args, **kwargs): http_response = <call_A_APIView> return Response({"message": http_response}) I have already tried the below code line: http_response = A.as_view()(request._request) But raise the below exception: You cannot access body after reading from request's data stream Any idea how to do it in the right way? -
Error in django that even chatgpt can't fix
error pictures I did post create, delete and update in django, then I created a dropdown to reach these pages. When I added the url extensions, I got an error in the extension, it looks in the pictures above, I asked chat gpt, the answers did not fix the error, whatever I did, it didn't work. -
Airflow task exited when calling django.setup(). No exception messages was printed
Trying to run django task with airflow. Has a local airflow setup. Tried example DAG and worked. Tried "Hello world" PythonOperator and worked. But when calling django.setup(), it exited with no exception message. Task log: *** Found local files: *** * /Users/st/airflow/logs/dag_id=exchange_rate_dag/run_id=manual__2023-06-27T20:16:11.857094+00:00/task_id=update_exchange_rate/attempt=1.log [2023-06-27, 20:16:13 UTC] {taskinstance.py:1103} INFO - Dependencies all met for dep_context=non-requeueable deps ti=<TaskInstance: exchange_rate_dag.update_exchange_rate manual__2023-06-27T20:16:11.857094+00:00 [queued]> [2023-06-27, 20:16:13 UTC] {taskinstance.py:1103} INFO - Dependencies all met for dep_context=requeueable deps ti=<TaskInstance: exchange_rate_dag.update_exchange_rate manual__2023-06-27T20:16:11.857094+00:00 [queued]> [2023-06-27, 20:16:13 UTC] {taskinstance.py:1308} INFO - Starting attempt 1 of 1 [2023-06-27, 20:16:13 UTC] {taskinstance.py:1327} INFO - Executing <Task(PythonOperator): update_exchange_rate> on 2023-06-27 20:16:11.857094+00:00 [2023-06-27, 20:16:13 UTC] {standard_task_runner.py:57} INFO - Started process 6674 to run task [2023-06-27, 20:16:13 UTC] {standard_task_runner.py:84} INFO - Running: ['airflow', 'tasks', 'run', 'exchange_rate_dag', 'update_exchange_rate', 'manual__2023-06-27T20:16:11.857094+00:00', '--job-id', '28', '--raw', '--subdir', 'DAGS_FOLDER/exchange_rate_dag.py', '--cfg-path', '/var/folders/cd/r_7zr7_x6nn32q2rk71pd5cw0000gn/T/tmpfqho3yoo'] [2023-06-27, 20:16:13 UTC] {standard_task_runner.py:85} INFO - Job 28: Subtask update_exchange_rate [2023-06-27, 20:16:13 UTC] {task_command.py:410} INFO - Running <TaskInstance: exchange_rate_dag.update_exchange_rate manual__2023-06-27T20:16:11.857094+00:00 [running]> on host ss-macbook-pro [2023-06-27, 20:16:13 UTC] {taskinstance.py:1545} INFO - Exporting env vars: AIRFLOW_CTX_DAG_OWNER='airflow' AIRFLOW_CTX_DAG_ID='exchange_rate_dag' AIRFLOW_CTX_TASK_ID='update_exchange_rate' AIRFLOW_CTX_EXECUTION_DATE='2023-06-27T20:16:11.857094+00:00' AIRFLOW_CTX_TRY_NUMBER='1' AIRFLOW_CTX_DAG_RUN_ID='manual__2023-06-27T20:16:11.857094+00:00' [2023-06-27, 20:16:13 UTC] {exchange_rate_dag.py:27} INFO - Finish setting stuff [2023-06-27, 20:16:13 UTC] {exchange_rate_dag.py:29} INFO - Finish set django setting modules [2023-06-27, 20:16:15 UTC] {local_task_job_runner.py:225} INFO - Task exited with return code 1 … -
Cannot get ManytoManyField content to display on my web page
I am having trouble accessing a list of data on a through table. The through table is called Cast and has a ManyToManyField for my Movie table (which lists every movie in the database) and another ManyToManyField for my Person table (which lists every actor). The fields need to be ManyToMany because an actor can appear in many different movies, and a movie can contain many different actors. I want to run a for-loop that lists all of the actors associated with a given movie (filtered by the movies primary key) and displays them on a web page. So far I cannot list anything on the web page (Movie.title displays the title, but I can't display anything from the Cast table.) I have tried reading all the other related stackoverflow solutions (such as listing objects from ManyToManyField) but I still cannot get the actor's names to display on the website. /Model.py class Movie(models.Model): title = models.CharField(max_length=250) class Person(models.Model): name = models.CharField(max_length=100) class Cast(models.Model): movie = models.ManyToManyField( Movie, ) castmember = models.ManyToManyField( Person ) /View.py class MoviePageView(TemplateView): template_name = '_movie_info.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['movie'] = Movie.objects.all() context['cast'] = Cast.objects.filter(movie__id=**kwargs) I have also tried: context['cast'] = Cast.objects.filter(movie__id=self.movie.id) context['cast'] = … -
Django urls.py not including the path
I'm relatively new to python and trying to make a django app. Can someone explain me why I'm running in to this issue with the include statement? The sql server says no module named 'website'. I think the problem is with the project structure, but I could not understand how to fix it. from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), # path('login/', views.login, name='login'), # path('logout/', views.logout, name='logout'), ] urls.py file in website folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include(website.urls)) ] urls.py file in crm folder -
uWSGI + Nginx don't generate the .sock file
I'm trying to deploy a Django app with uWSGI and Nginx like I always have done in the last 10 years but this time don't seem to work. Looks like there are permissions issues because the app.sock file is not created. This is my uwsgi.service: [Unit] Description=uWSGI Emperor service [Service] ExecStart=uwsgi --emperor /app/app/deployment/uwsgi.ini Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target This is my uwsgi.ini file: [uwsgi] # Ruta a la raiz del proyecto Django chdir = /app/app # Ruta al archivo wsgi.py del proyecto Django wsgi-file = /app/app/app/wsgi.py # Ruta al virtualenv del proyecto Django home = /app/app/.venv # Process-related settings master = true processes = %k threads = %(%k * 3) # The socket (use the full path to be safe) socket = /tmp/app.sock chmod-socket = 660 chown-socket = debian:www-data uid = www-data gid = www-data # Clear environment on exit vacuum = true # Location of log files logto = /var/log/uwsgi/%n.log # Respawn processes after serving 5000 max-requests = 5000 touch-chain-reload = %dreload listen = 40000 cpu-affinity = 1 max-fd = 200000 memory-report = 1 post-buffering = 1 This is my nginx.conf: server { listen 80; listen [::]:80; server_name 200.100.000.000; # Nuestro dominio o direccion IP charset utf-8; access_log … -
Django download via FileResponse or HttpResponse breaks csrf
In Django I'm trying to make a view that includes these two things: a link to generate and download a file via FileResponse a form to upload a file (posts to a separate view function) If the user uses those things in that order, django returns 403 csrf error. Some things I've tried, but still get csrf error: returning HttpResponse instead of FileResponse posting to the same view function setting CSRF_USE_SESSIONS = True for session-based instead of cookie-based csrf protection I'm curious to understand why this is happening and how to properly build this view. I am aware that @csrf_exempt can be used if csrf protection is not important. -
How to pg_dump only data from a table in a PostgreSQL database and pipe it into an identical but differently-named table in another database
Goal I need to copy just the data from a table in one database into another table in another database. The table in the target database has the exact same schema except that the name of the table is different. The two databases are on the same machine. Problem I can't find a way to pipe the data from pg_dump into a differently named table in the target database. What I've tried Here's the command I would use if the tables were named the exact same: pg_dump -a -t <table_name> <source_db> | psql <target_db> But where would I be able to put the name of the target table in the target database? Background info The reason I'm doing this is because I'm building a Django web-app, and I've realized I really need to separate a bunch of the models I've created into different 'apps' within my Django project. -
npydantic.error_wrappers.ValidationError: 1 validation error for XXX field required (type=value_error.missing)
I've edited the question as going round in circles trying to fix the original error. Here's the latest: Current error pydantic.main.BaseModel.__init__\npydantic.error_wrappers.ValidationError: 1 validation error for ConversationBufferMemory2\nchat\n field required (type=value_error.missing)\n', 'args': '[]', 'kwargs': llm.py chat = Chat.objects.get(id=chat_id) memory = ConversationBufferMemory2() memory.set_chat(chat) models2.py from langchain.memory.buffer import ConversationBufferMemory class ConversationBufferMemory2(ConversationBufferMemory): """Buffer for storing conversation memory.""" chat:Chat #def __init__(self,*args, **kwargs): # super().__init__(*args, **kwargs) def set_chat(self,chat:Chat): self.chat=chat @property def buffer(self) -> Any: """String buffer of memory. Each message is separated by a newline.""" if self.return_messages: return self.chat.messages # Think this is the right return type ? https://python.langchain.com/docs/modules/memory/ else: return get_buffer_string( self.chat.messages, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) ValidationError: File "/code/apps/llm_module/llm.py", line 183, in get_response\n memory = ConversationBufferMemory2()\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File "/usr/local/lib/python3.11/site-packages/langchain/load/serializable.py", line 74, in __init__\n super().__init__(**kwargs)\n File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__\npydantic.error_wrappers.ValidationError: 1 validation error for ConversationBufferMemory2\nchat\n field required (type=value_error.missing)\n', 'args': '[]', 'kwargs': -
Why my django urls don't work in production
My site works perfectly on local. But in production all links do not work, except homepage. Why homepage is so special i don't know. Browser shows 400 bad request. On the internet I found only allowed_host = [*], but I have it. Maybe I wrote something wrong in .htaccess or site.wsgi. Or are there special settings for urls in production? My hosting said that I may have errors in the code, but as I said in local it works. I use django 4.1 and python 3.8 setting.py from pathlib import Path from environs import Env env = Env() env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'news', 'additional_information', 'photoalbum', 'methods', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'kinder_garden.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/home/a0833083/domains/mysite.ru/public_html/kinder_garden/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
Can I get Django multiple admin sites, users, databases in a webapp?
I have a web app that is now working for a single business. It has users, a database, an admin site that the owner uses, and a few frontend pages through which the employees access it. I am planning to scale and the first idea was using several Django instances as subdomains (that way I just had to duplicate the code and manage routeing), but I soon realised that it would be pretty resource intensive. Is there are a way I can have multiple organizations use the webapp? All of them have the same use case so it should be less complex. I intensively use the Django users app for authentication and as a foreign key in databases so just cannot do without separate admin, users, and database for each business. The point where I encounter major issues is when trying to get different users for each of the business. Thanks a lot in advance! Edit: I just thought about another workaround, though it will take A LOT of coding. Basically making the Django admin by myself. I just need 3-4 functions out of admin: authentication, viewing models, adding users, and downloading databases in xls format. Is there a way …