Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with passing Django URL parameters while dynamically changing the inner HTML of a Django template using Javascript
I am trying to dynamically change the innerHTML of a Django template using Javascript. There are some anchor tags inside the HTML content. Their href contains Django URL with some parameters. There is some issue with it, but can't figure it out. $.ajax({ url: "{%url 'fact:datalist' %}", type: 'POST', headers: { "X-CSRFToken": token, }, dataType: 'json', data: { csrfmiddlewaretoken: token, seldata: selectedDate, } }).done(function (data) { const pdata = JSON.parse(data) pdata.forEach((key, index) => { const val = key.fields; console.log(val) const nid = val.result_id; trdata = `<tr> <td>${index}</td> <td style="display: none;"> ${nid} </td> <td><a href="{%url 'fact:entry_form' id=${nid} %}"> ${val.pdtcode} </a></td> <td> ${val.process_code} </td> <td> ${val.prev_count} </td> <td> ${val.ok_count} </td> <td> ${val.ng_count} `; if (val.ng_count != 0) { trdata = `<br><a href="{%url 'fact:editform' id=${nid} %}"> Edit </a>`; } trdata = `</td> <td> ${val.unattended_count}`; if (val.unattended_count != 0) { trdata = `<br><a href="{%url 'fact:checkform' id=${nid} %}"> Check </a>`; } trdata = `</td> </tr>`; $('.data_view>tbody').html(trdata) }); }) } The issue exists at the id=${nid} part of every URL. Need some advice to tackle this issue. Thanks in advance -
"ModuleNotFoundError: No module named" error for a local module in django
I have a local custom module that I want to use in my webservice but I got "ModuleNotFoundError: No module named" error. even when my editor can detect the module. At firs I think it was because of crontab that I'm using but even when I change ot to somthing else I still got this error. Even I changed the structure of my project and I still getting this error -
form validation error message not displaying
ther was no displaying error message in website and ther was no any elements for view errors view.py: from . import forms from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login,logout from django.core import validators def user_login(request): form=forms.LoginForm() if request.POST: form=forms.LoginForm(request) # if request.user.is_authenticated: # return redirect('home') return render(request,"login.html",context={'form':form,'message':''}) def home(request): if request.user.is_authenticated: return render(request,"home.html") return redirect(user_login) def user_logout(request): if request.user.is_authenticated and request.META.get('HTTP_REFERER') is not None: logout(request) return redirect(home) forms.py: from django import forms from django.core import validators class LoginForm(forms.Form): name= forms.CharField(validators=[validators.MinLengthValidator(4,"errorororokjjkkj hjkhjkjhk hkhkh j")],widget=forms.TextInput(attrs = {'class':"form-control mb-3",'placeholder':"Username"})) password=forms.CharField(widget=forms.PasswordInput(attrs = {'class':"form-control mb-3",'placeholder':"password"})) login.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>login</title> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <div class=" w-50 container " style="border-radius: 20px; background-color: darkgrey;"> <h1 class="mt-5 pt-5 mb-0 text-center ">login</h1> <div class="h-100 d-flex align-items-center justify-content-center "> <form class="w-50 m-5 container" method="post" > {%csrf_token%} {{form}} {{message}} <button type="submit" class="btn btn-primary mt-1" onclick="">login</button> </form> <!-- <form class="w-50 m-5 container" method="post" enctype="multipart/form-data" > {%csrf_token%} <label for="exampleFormControlSelect1">Username</label> <input type="text" class="form-control mb-3" placeholder="Username" name="username" required> <p>{{message}}</p> <label for="password">password</label> <input class="form-control mb-3" type="password" name="password" placeholder="password" required></input> <button type="submit" class="btn btn-primary mt-1" onclick="">login</button> </form> --> </div> </div> </div> </body> </html> i want display error without using … -
I have a field with current/permanent_address and I need to use this field with forward slash in my serializer
this is my serializer and I am not able to declare fields in my serilizer with forward slash "address": { "current/permenantAddress": { "PERM_LINE1": "delhi vasant vihar", "PERM_LINE2": "vasant vihar", }, "correspondence/localAddress": { "CORRES_LINE1": "", } } } -
100% CPU Utilization on my VPS - Django app gunicorn
I have a VPS running Nginx, Django, Postgres and a Golang microservice in a Docker compose environment and recently I've noticed it's consistently hitting 100% CPU utilization and not working anymore. I suspect this may be due to a DDoS attack or weird gunicorn behavior. VPS OS: Ubuntu 22.04.2 LTS Observations: The high CPU usage started around yesterday (24hrs ago). Steps Taken: Setup and config ufw, and a digitalocean firewall. NGINX Logs ... 89.44.9.51 - - [29/Sep/2023:05:09:58 +0000] "OPTIONS /webclient/api/MyPhone/session HTTP/1.1" 444 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 3CXDesktopApp/18.13.959 Chrome/112.0.5615.165 Electron/24.3.0 Safari/537.36" "-" 89.44.9.51 - - [29/Sep/2023:05:10:01 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:07 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:12 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:17 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:22 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:27 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:32 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" … -
insert the POST list to the db in Django?
We encountered a problem. Can you help? I am sending a list via POST. lists will be recorded in the table in two fields. Send List in HTML. As follows, validate result from html. Your list data are: ('csrfmiddlewaretoken', ['..']) ('x1', ['1', 'Закройный']) ('x2', ['2', 'Закройный']) ('x3', ['3', 'Закройный']) Models.py from django.db import models class Testmodel(models.Model): ws1 = models.CharField(max_length=100, blank=True) ws2 = models.CharField(max_length=100, blank=True) input.html <form action="../validate" method="POST"> {% csrf_token %} {% for work_stations in ws %} {% if work_stations.is_active %} <input name="x{{ work_stations.id }}" value="{{ work_stations.id }}"> <input name="x{{ work_stations.id }}" value="{{ work_stations.category }}"> {% endif %} {% endfor %} <input type="submit" > </form> views.py from django.shortcuts import render from .models import Testmodel def createpost(request): if request.method == 'POST': list_data = (list(request.POST.lists())) #Here I need to save list_data to the database. The following code does not work. mylist = list_data Testmodel.objects.bulk_create([Testmodel(**{ 'ws1' : x[0], 'ws2' : x[1]}) for x in mylist]) -
Django, MySQL tests create all tables, but why is each table empty?
Problem Statement: When I use any test case that tries a db lookup I get a typical db error like "matching query does not exist." I cannot figure out why test db creation creates the tables, but fails to put the data into the tables. Using MySQL db in development works fine. So Far: Performed significant amounts of searching for similar issues posted by others, but failed to find any I used --keepdb and found that all tables successfully create, however, they are all empty; even tables like auth_user. Work around: I can manually add data to the test tables and reach a successful test case with a db query (yay!), however, it is a super pain and not easily repeatable (or sustainable). =========================== Notes: Migrations are regularly deleted from django_migrations table and the migrations directory with subsequent make and fake. The standalone migration file; 0001_initial.py looks good. Using typical database settings, no test db defined, no mirrors. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': 'localhost', 'PORT': '3306', } } -
Manually validating csrftoken in Django
<script> const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; let submitFormData = () => { const formData = new FormData(); // Add form data // This line may not be required as the header contains it formData.append('csrftoken', csrftoken); const request = new Request( URL, {headers: {'X-CSRFToken': csrftoken}} ); return fetch(request, { method: 'POST', mode: 'same-origin', body: formData }) .then(response => response.json()) .then(response => { data = response['time']; return data; }); } </script> How do I validate csrftoken on the server side in Django / python ? I am not using DRF here. Django 4.2 -
Django ,How can I display account details when I select it?
** for my problem, I find it very complex and I researched it a lot and did not find a solution. I hope for your support I want when I choose the account, whether a parent or a child, to display it with the rest of its details on the other side of the template[![enter image description here][2]][2] ** -
DJango - JS - Ajax - Upload file to NRM/Nexus (another domain) - CORS Issue
PLEASE HELP With the following JS function `function nexusUploader(file) { let filename = file.name, formData = new FormData(); formData.append('package', file); $.ajax({ url: "https://<external domain (NRM/NEXUS)>", type: "PUT", data: formData, contentType: false, cache: false, cors: false , crossDomain: true, secure: true, processData: false, mimeType: "multipart/form-data", headers: { 'X-CSRFTOKEN': $.cookie("csrftoken"), "Authorization": "Basic <KEY>" }, success: function(data) { console.log(data); }, error: function(e) { console.log(e); } }); }` I am getting the following error: Access to XMLHttpRequest at 'https://' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. global.js:37 09/28/2023 22:06:20: {readyState: 0, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} jquery-3.7.0.min.js:2 PUT https:// net::ERR_FAILED -
'MoneyField' object has no attribute '_currency_field' in django-money when running migration
For the following Model, I added a new field gst_amount: from djmoney.models.fields import MoneyField class Invoice(Model): gst_amount = MoneyField(max_digits=14, decimal_places=2, default="0 USD") The migration completed and I can use the field in my views without issue. When I try to run the following data migration: from djmoney.money import Money from django.db import migrations def migrate_invoices(app, _): Invoice = app.get_model("users", "Invoice") for invoice in Invoice.objects.all(): invoice.gst_amount = Money(10, 'AUD') class Migration(migrations.Migration): operations = [ migrations.RunPython(migrate_invoices, migrations.RunPython.noop) ] I get the following error: File "/app/blah/users/migrations/0159_auto_20230929_0113.py", line 9, in migrate_invoices for invoice in Invoice.objects.all(): File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 69, in __iter__ obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 515, in from_db new = cls(*values) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 437, in __init__ _setattr(self, field.attname, val) File "/usr/local/lib/python3.9/site-packages/djmoney/models/fields.py", line 111, in __set__ and self.field._currency_field.null AttributeError: 'MoneyField' object has no attribute '_currency_field' Not sure what I'm missing? -
How do I make these Tables?
We'll have to make these tables in HTML, but I'm not sure how to do them. [[These are the images of the tables. We have to use DJango and add them info there. But we are not sure how to desing the tables ourselves, how to make one cell in a row and then 2 cells.](https://i.stack.imgur.com/Gx1dS.png)](https://i.stack.imgur.com/ggbHz.png) Another example: | Column A | Column B | | -------- | -------- | | Cell 1 | | Cell 2 | Cell 3 | | Check Marck o | | Cell 4 | Image | <table border="1" width="70%"> <caption>Listado Clientes Septiembre 2023</caption > <tr> <th>Codigo de venta</th> <th>Precio del Producto</th> <th>Cantidad</th> <th>Valor unitario</th> <th>Total a pagar</th> </tr> <tr> <td>{{CCodigoVenta}}</td> <td>{{PProducto}}</td> <td>{{CCantidad}}</td> <td>{{ValorUnitario}}</td> <td>{{TTotalPagar}}</td> </tr> </table> That's how we made a table like the third image, but I don't know how to make something like the Cell 1, or puit a check mark for example. qwp -
Issue with outputting tolls using Google routes API
I am able to get toll information correctly using Google routes Api when running the code on localhost. Response on localhost is : {'routes': [{'legs': [{'travelAdvisory': {'tollInfo': {'estimatedPrice': [{'currencyCode': 'INR', 'units': '170'}]}}}], 'distanceMeters': 112558, 'duration': '7729s', 'travelAdvisory': {'tollInfo': {'estimatedPrice': [{'currencyCode': 'INR', 'units': '170'}]}}}]} When the same code is migrated to cloud server , toll information becomes blank. Response on Cloud comes like this : {'routes': [{'legs': [{}], 'distanceMeters': 112558, 'duration': '7729s'}]} Expecting the same response on cloud as it is coming on localhost because code is same. -
Django Rest and Dropzone React "The submitted data was not a file. Check the encoding type on the form."
I've got a react frontend with django backend trying to upload some images to django api enpoint I have 1 model in django but i want to first upload an image and then submit the rest of the data, the issue is when i try to upload the photos i get an error response photos [ "The submitted data was not a file. Check the encoding type on the form." ] I am using Dropzone to upload photos by the way Here is the react component handling uplaod function ImageUploader() { const [fileNames, setFileNames] = useState([]); const handleDrop = async (acceptedFiles) => { try { // Create a new FormData object to send files const formData = new FormData(); acceptedFiles.forEach((file) => { // Append each file to the FormData object formData.append('photos', file); }); // Make a POST request to your photo upload endpoint //axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'; const response = await axios.post('http://localhost:8000/api/quotes/create/', formData, { headers: { 'Accept': 'application/json', 'Content-Type': 'multipart/form-data', }, }); // Handle the response (e.g., show success message) console.log('Upload successful:', response.data.message); // Update the list of file names for display setFileNames(acceptedFiles.map((file) => file.name)); } catch (error) { console.error('Upload failed:', error); } }; return ( <div className="App"> <Dropzone onDrop={handleDrop} accept={{ … -
ModuleNotFoundError: No module named 'simple_history' Pythonanywhere
I have a Django app running on pythonanywhere server. I have installed the requirements.txt and everything is okay, python manage.py migrate also successfully done. now when I reload my app I get following error. 2023-09-29 00:42:43,481: Error running WSGI application 2023-09-29 00:42:43,514: ModuleNotFoundError: No module named 'simple_history' 2023-09-29 00:42:43,514: File "/var/www/app_umrahpro_me_wsgi.py", line 16, in <module> 2023-09-29 00:42:43,514: application = get_wsgi_application() 2023-09-29 00:42:43,514: 2023-09-29 00:42:43,514: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2023-09-29 00:42:43,515: django.setup(set_prefix=False) 2023-09-29 00:42:43,515: 2023-09-29 00:42:43,515: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup 2023-09-29 00:42:43,515: apps.populate(settings.INSTALLED_APPS) 2023-09-29 00:42:43,515: 2023-09-29 00:42:43,515: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate 2023-09-29 00:42:43,516: app_config = AppConfig.create(entry) 2023-09-29 00:42:43,516: 2023-09-29 00:42:43,516: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/apps/config.py", line 193, in create 2023-09-29 00:42:43,516: import_module(entry) 2023-09-29 00:42:43,516: *************************************************** 2023-09-29 00:42:43,520: If you're seeing an import error and don't know why, 2023-09-29 00:42:43,520: we have a dedicated help page to help you debug: 2023-09-29 00:42:43,521: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2023-09-29 00:42:43,521: *************************************************** It should be reloaded without any error -
Docker Error build during Deployment on Railway services
please I had previously deployed my Django project on Railway which worked fine. Unfortunately, when I tried to add up SendGrid mail functionality by using django-sendgrid-v5 package to help me handle that, everything worked pretty well in the development environment including SendGrid mails like Signup user. However, when I deployed it on Railway which uses Nixpacks to manage its default project build, I kept getting this weird error that ENV cannot be blank. I followed their deployment procedures on Python since they have a similar deployment infrastructure to Heroku. I made sure that all the (env) variables needed to run the project in their platform were set correctly. I had checked my settings.py files and my .env files to know whether I was missing anything there, but I could not find the error. I even uninstall the django-sendgrid-v5 which I believed could have introduced the error, still my deployment kept on crashing. Below is the deployment build code which has been persistent. ` ╔══════════════════════════════ Nixpacks v1.16.0 ══════════════════════════════╗ ║ setup │ python310, postgresql, gcc ║ ║──────────────────────────────────────────────────────────────────────────────║ ║ install │ python -m venv --copies /opt/venv && . /opt/venv/bin/activate ║ ║ │ && pip install -r requirements.txt ║ ║──────────────────────────────────────────────────────────────────────────────║ ║ start │ python … -
MultiValueDictKeyError at /register
I keep getting this whenever I try to register a user on my test website using Django please can anyone help me out MultiValueDictKeyError at /register 'email' Request Method: POST Request URL: http://localhost:8000/register Django Version: 4.2.5 Exception Type: MultiValueDictKeyError Exception Value: 'email' Exception Location: C:\Users\user\Envs\myapp\lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: myapp.views.register Python Executable: C:\Users\user\Envs\myapp\Scripts\python.exe Python Version: 3.10.9 Python Path: ['C:\Users\user\Desktop\Python Tutorial\Django tutorials\myproject', 'C:\Users\user\anaconda3\python310.zip', 'C:\Users\user\anaconda3\DLLs', 'C:\Users\user\anaconda3\lib', 'C:\Users\user\anaconda3', 'C:\Users\user\Envs\myapp', 'C:\Users\user\Envs\myapp\lib\site-packages'] here is views.py code def register(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] repeat_password = request.POST['repeat password'] if password == repeat_password: if User.objects.filter(email=email).exists(): messages.info(request, 'Email Already Used') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request, 'Username Already Used') return redirect('register') else: user = User.objects.create_user(username=username, email=email, password=password) user.save(); return redirect('login') else: messages.info(request, 'Password Not The Same') return redirect('register') else: return render(request, 'register.html',) -
how to pass a string variable in django urls?
so i made a variable named urlname in my django model and want to pass it in my urls like this: path('example/<str:url>/', views.example, name='example'), and in my views i did this: def example(request, url): example = Example.objects.get(urlname=url) context = {'example':example} return render(request, 'example/example.html', context) lets say in the models, urlname has the value 'test'. when i enter the url 'example/test/' in my browser it gives me this error: ValueError at /example/test/ Field 'id' expected a number but got 'test'. i've read and checked my code, im pretty new at coding, i hope i get my answer here and my explanation was not unclear. -
Creating a wrapper for a Python3 based project with Django
Calling for help!! I have a python3 based project (it's a huge one with a lot of command line interfaces and tools/scripts running off of it) that's basically used as a resource repo. This was actually written in python2 and I am in process of migrating it over to python3. The guy who wrote this used django.models as a way to interact with the DB. Mind you, this wasn't a django project! Now, what I am thinking is, how can I migrate this project and get it to use the same everything, by just creating a django app that wraps the models for it, without disrupting anything else?! I don't have any idea regarding where to start this from and am looking forward to suggestions from developers who have done similar sort of work! -
Django rest framework API View
I am trying to make an API view for a custom user model, however I get the following error (Method Not Allowed: /api/v1/users/create), also when I access the API through the browser I get none of the custom fields, but instead I get a media type and a content block. The serializer: class UserSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) first_name = serializers.CharField() last_name = serializers.CharField() email = serializers.EmailField() phone = serializers.IntegerField() password = serializers.CharField(write_only=True) ``` The View: ``` class CreateUser(APIView): def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data return Response(serializer.data) ``` The url: `path('users/create', CreateUser.as_view()),` I expect to get the api view with the first_name, last_name, etc fields to create a user -
How to prevent the user from changing some fields in Django Rest?
My Django REST application has an entity where during creation/update some fields are set by the backend and not by the user, but the user can still submit requests to update these fields. Fields to change only by backend: by_backend_only = [ "company", "schedule_format", "file_url", "is_valid", "err_msg", "total_flights" } Serializer: class ScheduleSerializer(ModelSerializer): class Meta: model = RP_Schedule fields = [ "id", "name", "season", "airport", "company", "schedule_type", "schedule_format", "file_url", "err_msg", "is_valid", "total_flights", "date_range_start", "date_range_end", ] How can I prevent the user from changing these fields, but leave them in the serializer to create/update entities? -
Google analytics not tracking specific page views
Issue: When checking google analytics specific pages on my site are not being tracked. It just shows my websites name for every page view. Code: base .html <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-11111"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-11111'); </script> other pages: {% extends "blog/base.html" %} From what I can tell its configured correctly as it seems to be tracking events properly Cant seem to track down the cause. -
EnumType.__call__() missing 1 required positional argument: 'value' in Djano admin panel (blogs - posts)
when I was customizing my admin panel in Django , this error happened : EnumType.call() missing 1 required positional argument: 'value' in Djano admin panel (blogs - posts) enter image description here This is my admin.py code : from django.contrib import admin from .models import * Register your models here. @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ['title','author' ,'publish', 'status' ] my app name is Blog and class name is POST then I added at the end of this code (deleted @admin.register(Post)): #admin.site.register(Post,PostAdmin) SO WHAD SHOUD I DO ??????? -
Multiple django-tenants using only one domain
I have a Django application running, right now we have different schemas into different subdomains (ex: schema 1: subdomain1.domain.com, schema 2: subdomain2.domain.com). I need to change this for different schemas into one domain. Problems: Authentication: today the auth is made in TENANT_APPS, but I think that need to change, for the auth works. Maintaining the session: I tried some solutions, but the times I managed to authenticate the user, the session was not maintained or was not created, so I could not navigate through the application. Can somebody help me? I've tried some of the issues in django-tenants (https://github.com/django-tenants/django-tenants) -
pytest-django ERROR django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured
I have a Django project with pytest and pytest-django packages. I have an app "api" with tests/ folder with all of my tests. After running pytest in the terminal, I get an error: ==================================================== short test summary info ===================================================== ERROR apps/api/tests/test_db_queries.py - django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must eithe... !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ======================================================== 1 error in 0.45s ======================================================== I have a test to test my User model. When I don't use my model and delete import from api app everything is working fine. settings.py is in meduzzen_backend folder. test_db_queries.py: import pytest from api.models import User # Create your tests here. @pytest.mark.django_db def test_queries_to_db(): User.objects.create(username="sfdf") users = User.objects.all() assert len(users) == 1 My project hirearchy: ├───.pytest_cache │ └───v │ └───cache ├───apps │ └───api │ ├───migrations │ │ └───__pycache__ │ ├───tests │ │ └───__pycache__ │ └───__pycache__ ├───code └───meduzzen_backend └───__pycache__ My tests/ folder has __init__.py file. pytest.ini: [pytest] DJANGO_SETTINGS_MODULE = meduzzen_backend.settings python_files = tests.py test_*.py *_tests.py Where is the problem? I've tried to rename my api app in INSTALLED_APPS setting in settings.py from: INSTALLED_APPS = [ ... # Django apps 'api.apps.ApiConfig', ... ] to: INSTALLED_APPS = [ ... # Django apps 'api', ... ] …