Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pywinrm CredSSP NTLM BadMechanismError(context_msg="Unable to negotiate common mechanism", base_error=last_err)
I am trying to debug strange behaviour when using the pywinrm. It cannot open WinRM connection because of BadMechanismError: SpnegoError (1): expected string or bytes-like object, got 'dict', Context: Unable to negotiate common mechanism I am using it in a docker and the same image behaves differently. Running the image on one server produces error message below, running on different server I am not able to figure out what can be different 2024-06-27T14:38:56+0000 DEBUG _credssp MainProcess-10 MainThread-139775582927656 _step_initiate : Starting CredSSP authentication phase 2024-06-27T14:38:56+0000 DEBUG _negotiate MainProcess-10 MainThread-139775582927656 step : SPNEGO step input: 2024-06-27T14:38:56+0000 DEBUG _negotiate MainProcess-10 MainThread-139775582927656 _rebuild_context_list : Attempting to create kerberos context when building SPNEGO mech list 2024-06-27T14:38:56+0000 DEBUG _negotiate MainProcess-10 MainThread-139775582927656 _rebuild_context_list : Failed to create context for SPNEGO protocol kerberos: Configuration file does not specify default realm -1765328160 2024-06-27T14:38:56+0000 DEBUG _negotiate MainProcess-10 MainThread-139775582927656 _rebuild_context_list : Attempting to create ntlm context when building SPNEGO mech list 2024-06-27T14:38:56+0000 DEBUG _negotiate MainProcess-10 MainThread-139775582927656 _rebuild_context_list : Failed to create context for SPNEGO protocol ntlm: expected string or bytes-like object, got 'dict' 2024-06-27T14:38:56+0000 ERROR exception_handler MainProcess-10 MainThread-139775582927656 process_exception : (500) Exception occurred: Received error status from the server: (2148074245) UNKOWN_STATUS 0x80090305 2024-06-27T14:38:56+0000 ERROR exception_handler MainProcess-10 MainThread-139775582927656 process_exception : Received error … -
Issue with Django admin form: Custom file upload field affecting unrelated form field
I'm currently working on a Django project where I've extended the admin form to allow for multiple file uploads. I am following this article. However, I'm encountering an issue where my custom file upload field seems to be affecting an unrelated form field (property_title). Specifically, after implementing the custom file upload field, the value of property_title is being changed to the name of the uploaded image. Here is simplified version of my setup: Models: from django.db import models class Property(models.Model): property_title = models.CharField(max_length=100) # Other fields class PropertyImage(models.Model): property = models.ForeignKey(Property, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='property_images/') Admin.py: from django.contrib import admin from .models import Property, PropertyImage from .forms import PropertyAdminForm class PropertyImageInline(admin.TabularInline): model = PropertyImage extra = 1 @admin.register(Property) class PropertyAdmin(admin.ModelAdmin): inlines = [PropertyImageInline] Change_form.html: {% extends "admin/change_form.html" %} {% block inline_field_sets %} {% for inline_admin_formset in inline_admin_formsets %} {% include inline_admin_formset.opts.template %} {% endfor %} <fieldset class="module"> {% comment %} <label for="id_photos_multiple">Upload Multiple Photos:</label> {% endcomment %} <h2>Upload Photos</h2> <input name="photos_multiple" type="file" multiple accept="image/*" /> </fieldset> {% endblock %} How can I implement this setup so that I will be able to upload multiple images without effecting other fields of the form. This issue which I figure out is … -
Django Test Case Failing: Function Not Returning Expected Sum of Related Model Fields
I am working with Django 4.2.2 and I have a test case that is failing because a custom function is not returning the expected sum of related model fields. so this is my test: class UnitaImmobiliareModelTest(TestCase): def setUp(self): self.user = User.objects.create_user(username='UtenteTest', password='testing') self.studio = Studio.objects.create( nome_studio="Studio Test", utente_creatore_studio=self.user ) self.commessa = Commesse.objects.create( anno=timezone.now(), nome_commesse="Commessa Test", numero_commesse="0001", descrizione="Descrizione della commessa", somme_utilizzabili=10000, tipo_committente=True, utente_creatore=self.user, studio_associato=self.studio, utente_permesso=True ) self.preventivoCommessaFase = PreventivoCommessaFase.objects.create( codice="0001", nome="test", descrizione="testing", commessa=self.commessa, costi=2.00, ) self.fasiPrestazionali = FasiPrestazionali.objects.create( nome_fase="test001", costo=3, preventivi_commessa = self.preventivoCommessaFase ) self.unitaImmobiliare1 = UnitaImmobiliare.objects.create( codice="0002", descrizione="test", latitudine=2.2, longitudine=1.2, utente_creatore_unita=self.user, preventivi_fase=self.preventivoCommessaFase ) self.unitaImmobiliare2 = UnitaImmobiliare.objects.create( codice="0003", descrizione="test", latitudine=2.2, longitudine=1.2, utente_creatore_unita=self.user, preventivi_fase=self.preventivoCommessaFase ) def test_calcola_spesa_totale(self): expected_spesa_totale = Decimal('4.00') result = calcola_spesa_totale(self.preventivoCommessaFase) self.assertEqual(result, expected_spesa_totale) i am trying to test the func "calcola_spesa_totale" : print(f"QuerySetData: {computi}") print(computi[1].preventivi_fase.costi) totali_unita_immobiliari = ( computi.values("descrizione") .annotate(totale_costo=Sum(Cast("preventivi_fase__costi", FloatField()))) .order_by("descrizione") ) print(f"somma totale: {totali_unita_immobiliari}")#asd spesa_totale = sum( Decimal(item["totale_costo"] or 0) for item in totali_unita_immobiliari ) print(f"Spesa Totale Calcolata: {spesa_totale}") #asd return spesa_totale` ` problem is by the time i get inside this function, the error has already occured meaning that, the value of preventivi_fase.costi has already been set to 0.0 by my investigation this happens inside the Model PreventivoCommessaFase def totale_fasi this is the other model FasiPrestazionali containing … -
cannot import name 'AggsProxy' from 'elasticsearch_dsl.search'
my pip installs are elastic-transport==8.13.1 elasticsearch==8.14.0 elasticsearch-dsl==8.14.0 django-elasticsearch-dsl==8.0 django-elasticsearch-dsl-drf==0.22.5 services: elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:8.14.0 environment: - xpack.security.enabled=false - discovery.type=single-node ports: - "9200:9200" volumes: - elasticsearch-data:/usr/share/elasticsearch/data volumes: elasticsearch-data: -
Django web app was blocked due to MIME type (“text/html”) mismatch
I am trying to build a web-app with Django with a front-end made with Vue.js. Here is how my dir is organized - reco_system_app/urls.py reco_system_app/settings.py recommender/urls.py recommender/views.py vueapp/ static/ templates/ reco_system_app/urls.py is from django.contrib import admin from recommender.views import home from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('recommender.urls')), path('', home, name='home'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py has these two set STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] recommender/urls.py is from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('movies/', views.get_random_movies, name='get_random_movies'), path('recommend/', views.get_recommendations, name='get_recommendations'), ] view.py is import random from django.shortcuts import render from django.views.generic import TemplateView from django.http import JsonResponse class IndexView(TemplateView): template_name = 'index.html' def home(request): return render(request, "index.html") def get_random_movies(request): # Simulate a list of movies sample_movies = ["The Shawshank Redemption", "The Godfather", "The Dark Knight", "Pulp Fiction", "The Lord of the Rings: The Return of the King"] # Return a random sample of 5 movies movies = random.sample(sample_movies, 3) return JsonResponse({"movies": movies}) def get_recommendations(request): # For simplicity, assume the movies are passed as a comma-separated string in the query parameter selected_movies = request.GET.get('movies', '') selected_movies_list = selected_movies.split(',') … -
(debug_toolbar.E001) The Django Debug Toolbar can't be used with tests
The complete error message is as below ?: (debug_toolbar.E001) The Django Debug Toolbar can't be used with tests HINT: Django changes the DEBUG setting to False when running tests. By default the Django Debug Toolbar is installed because DEBUG is set to True. For most cases, you need to avoid installing the toolbar when running tests. If you feel this check is in error, you can set `DEBUG_TOOLBAR_CONFIG['IS_RUNNING_TESTS'] = False` to bypass this check. How to recreate: Install django-debug-toolbar by running pip install django-debug-toolbar Run your test cases using python manage.py tests I could not find this question anywhere on StackOverflow. Hence, I'm posting this and answering it. -
Django failing to use its own UUID, tries to do a hex replace errors with new items added to model
This is happening on both my local and my prod solution, both are new Django projects and no data is transferred between them (new db every time). Whenever I try to make a new entry in one of my models, it throws a AttributeError 'int' object has no attribute 'replace' Initially I thought it was something wrong with my code that writes data into the db, but I found its happening when I try and enter something new via the admin panel. Tracing it back further it appears to be coming from the internal code trying to clean up the UUID but failing: hex = hex.replace('urn:', '').replace('uuid:', '') I'm pretty lost as to what to do next given this is internal Django code that's throwing a fit and I'm not giving it the UUID values, those are coming from my model which uses their recommended code: class Articles(models.Model): # Fields id = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) title = models.CharField(max_length=256,blank=False,null=False,help_text="", verbose_name="Article Title") url = models.URLField(blank=False,null=False, help_text="", verbose_name="Article URL") image_url = models.CharField(max_length=512,blank=False,null=False,help_text="", verbose_name="Image Reference") site = models.ForeignKey(Sites, on_delete=models.CASCADE) published = models.DateField(null=True, blank=True, help_text="The date the article was published", verbose_name="Published Date") created = models.DateTimeField(auto_now_add=True,null=True, blank=True, help_text="The date the article was created in the site", verbose_name="Created … -
HI, I'M A FIRST TIME DJANGO USER
It's my first time using django. I have an error on running the server. the terminal says that django couldnt find my 'settings' module.What should i do? This is what blackbox.ai says "The error message indicates that Django is unable to find the settings module in your project. This is likely because the DJANGO_SETTINGS_MODULE environment variable is not set correctly." I tried my best but still can't solve the problem -
Python Django admin side request and approval
Behalf of gym management project I need to request trainer to get access to gym website so, when trainers requested with his personal and professional details then, the admin can view the details and approve or delete request. When it approved it automatically save to db . How will I do this in python Django I searched for a long, But i can't -
Social Login with Django Rest Framework and Dj-rest-auth
I have configured social login with Google with dj-rest-auth and Django rest framework. When I sign-up using normal the normal register view from dj-rest-auth, I can't login using the Gmail of same account. E.g I sign-up up normally using register with email: ifeanyinneji777@gmail.com. and then I tried logging in with Google with the same email. It says that a user with this email address already exists. Expecting to be logged in properly using Google. -
Django admin tabularinline similar queries
I'm developing an online store using Django. I have a main class Product class Product(models.Model): our_code = models.CharField('Наш артикул', max_length = 255, unique=True, blank=True, null=True) name = models.CharField('Наименование',max_length = 255, blank=True, null=True) full_name = models.CharField('Полное наименование',max_length = 255, blank=True, null=True) PRICE_TYPE_CHOICES = [ ('manual', 'Ручная установка'), ('rrc', 'РРЦ'), ('mrc', 'МРЦ'), ] CURRENCY_TYPE_CHOICES = [ ('rub', 'RUB (₽)'), ('usd', 'USD ($)'), ('eur', 'EUR (€)'), ('gbr', 'GBP (£)'), ] price_type = models.CharField('Тип цены',max_length=10, choices=PRICE_TYPE_CHOICES, default='manual') manual_price = models.DecimalField('Ручная цена',max_digits=20, decimal_places=2, blank=True, null=True) rrc_price = models.DecimalField('РРЦ', max_digits=20, decimal_places=2, blank=True, null=True) mrc_price = models.DecimalField('МРЦ', max_digits=20, decimal_places=2, blank=True, null=True) currency = models.CharField('Валюта',max_length=10, choices=CURRENCY_TYPE_CHOICES, default='rub') price_currency = models.DecimalField('Цена в валюте', max_digits=20, decimal_places=2, blank=True, null=True) text_short = models.TextField('Краткое описание', blank=True, null=True) text_full = models.TextField('Полное описание', blank=True, null=True) Associated with it is the ProductWith class, which stores similar products and is displayed in the Product class in the admin panel class ProductWith(models.Model): product = models.ForeignKey(Product, related_name='primary_product_with', default=None, on_delete=models.CASCADE, verbose_name='Товар') product_with = models.ForeignKey(Product, related_name='product_with_products_with', default=None, on_delete=models.CASCADE, verbose_name='Советуем купить') code admin.py class ProductWithAdmin(admin.TabularInline): model = ProductWith fk_name = 'product' extra = 0 raw_id_fields = ('product_with',) autocomplete_fields = ('product_with',) class ProductAdmin(admin.ModelAdmin): inlines = (ProductProviderAdmin, ProductImageAdmin, ProductAnalogAdmin, ProductColorAdmin, ProductWithAdmin,) search_fields = ['name', 'our_code'] autocomplete_fields = ["category", "manufacturer", "provider"] The problem is that … -
Gunicorn service stopping under supervisor with docker
I've using supervisor, nginx and gunicorn to deploy Django project with Docker. I'm running docker-compose up to build the project and nginx image. Going through other similar issues, it is recommended to use absolute path such as /home/ubuntu/... But since I'm using docker containers to run the project where I'm copying project in /app with COPY . /app/. I'm confused as to what write in directory in supervisor file. Below is my supervisor configuration. [supervisord] nodaemon=true [program:gunicorn] command=gunicorn trade_calls.wsgi:application --bind 0.0.0.0:8000 directory=/app user=root autostart=true autorestart=true stderr_logfile=/var/log/gunicorn.err.log stdout_logfile=/var/log/gunicorn.out.log [program:nginx] command=nginx -g "daemon off;" autostart=true autorestart=true stderr_logfile=/var/log/nginx.err.log stdout_logfile=/var/log/nginx.out.log The error I'm facing is docker-compose logs -f web web-1 | 2024-06-26 21:41:45,768 CRIT Supervisor is running as root. Privileges were not dropped because no user is specified in the config file. If you intend to run as root, you can set user=root in the config file to avoid this message. web-1 | 2024-06-26 21:41:45,771 INFO supervisord started with pid 1 web-1 | 2024-06-26 21:41:46,775 INFO spawned: 'gunicorn' with pid 7 web-1 | 2024-06-26 21:41:46,779 INFO spawned: 'nginx' with pid 8 web-1 | 2024-06-26 21:41:47,365 WARN exited: gunicorn (exit status 3; not expected) web-1 | 2024-06-26 21:41:48,368 INFO spawned: 'gunicorn' with pid 11 web-1 … -
Broken Process Pool: Processpool executor inside django app hosted on apache
I have a django application that I would like to host on my apache server. Use case of the application is to receive requests and performs compute intensive operations over a set of given inputs. To parallelise my computations I used future.ProcessPool executor in the core of the django app. Parallelisation in indispensable for my application. While the above setup works locally, I face BrokenProcessPool error especially when the app is hosted on the apache server. Tried few tricks in some related questions (here) but I have no clear idea what is happening or how to resolve it. Could someone please help me understand: Technically, what is the underlying issue in my setup? How do I resolve it without massively changing my existing framework(Django, Apache)? Can you provide me references for an ideal workflow used in some well known data-science or graphics web applications using Django and parallel computations. This could help me revise my current framework. Below is some relevant information views.py looks like import core.ray_trace def get_heatmap(request): list_of_inputs = request.POST.get('inputs') # parallel computation of list happens inside raytrace response_data = ray_trace(list_of_inputs) return JsonResponse(response_data, status=200) Apache config for my project WSGIDaemonProcess sp python-path=/home/ubuntu/_/spaceplanning python-home=/home/ubuntu/_/venv processes=3 threads=10 request-timeout=600 WSGIProcessGroup sp … -
How to serve static files for django-cms on DigitalOcean
I have deployed a django-cms app on DigitalOcean following the steps in this tutorial: https://www.digitalocean.com/community/tutorials/how-to-deploy-django-to-app-platform The app is up and running but static-files are not served. I created the additional static site refering to the same github repository and it is up and running too. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [ BASE_DIR / "project_name" / "static", ] I did collect the static files with python manage.py collectstatic and the folder and files are present in the intended location. How do I "connect" the app on DigitalOcean to my static files? -
Django Rest Framework Api and seperate html css frontend
I make a django project where i made a model of product. i send this data through api in json form. In seprate html css js page i fetch the api and show all my data product. but i could not find the image solution to solve this issue. because url is passed by json but issue is that how we gave the path by frontennd where that image exists. i want to show that image on frontend that is placed at different place fron django project. what would be best approach or refer me some articles related to it. -
Django 'IntegerField' object has no attribute 'get_internal_type'
So guys i have been trying to use the ExpressionWrapper in django and get outputfield as a IntegerField(), I don't know where I am going wrong The imports # Imports from django.core from attr import fields from django.db import models from django.db.models import DecimalField, IntegerField, Avg,Subquery,OuterRef, Q, Sum, F, ExpressionWrapper from django.db.models.functions import ExtractYear from django.contrib.auth.models import User from django.forms import DateField, DecimalField, IntegerField from django.shortcuts import get_object_or_404 from django.utils import timezone # Imports froms apps from shop.models import CartItem, Order, OrderItem, Product, Review from wallets.models import Transaction, Wallet This is code part of a model method Profile.objects.filter( id__in = Wallet.objects.filter( id__in=purchases_made_for_on_store_products.values('wallet') ).values('user') ).values('dob').annotate( age = ExpressionWrapper(ExtractYear(dt.today()) - ExtractYear(F('dob')), output_field=IntegerField())) ) I was expecting the code to calculate the age of each of each user and store it temporarily in in a field called "age". this would allow me to annotate it and further used for filtering. -
Getting Error: Forbidden (CSRF cookie not set.) when trying to make a post request to Django view
I am trying to create a (chrome extension + Django) password manager that will read input boxes from forms and on clicking submit it will make a POST request to the Django view with the data which will then get stored on to the postgresql database. (Keep in mind, this is only a personal project.) But on every request, I get the error: Forbidden (CSRF cookie not set.). Even though I see csrftoken cookie under the Applications tab in inspect. I am passing the csrf token along with the request so I can't figure out what the error is. I have tried getting the csrf token from cookies using Cookies.get('csrftoken') and also setting the csrf token cookie after fetching it from Django as well. This is what my view looks like in Django : @ensure_csrf_cookie def add(request): if request.method == "POST": website = request.POST['website'] username = request.POST['username'] password = request.POST['password'] user = request.user encryptedPass = cryptography.crypto(password) credentials = Credentials.objects.create(email=username, password=encryptedPass) if Website.objects.filter(user = user.id).filter(name=website).exists(): website_obj = Website.objects.filter(user = user.id).filter(name=website) # print(website_obj[0].credentials) website_obj[0].credentials.add(credentials) else: website_obj = Website.objects.create(user=user, name=website) website_obj.credentials.add(credentials) if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return JsonResponse({'message':'Credentials Add'}) return redirect('add') return render(request,'add.html') This is the view where I pass the csrf token to … -
Permission Denied and Python Module Issues when Deploying Django with Apache on Ubuntu
I'm encountering difficulties while trying to deploy my Django website using Apache on an Ubuntu server. Here are the details of the problem: Error Messages: Current thread 0x00007e9faacab780 (most recent call first): <no Python frame> [Thu Jun 27 02:58:10.538441 2024] [wsgi:warn] [pid 16762:tid 139224230311808] (13)Permission denied: mod_wsgi (pid=16762): Unable to stat Python home /home/robch/TestSite/django_env. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/robch/TestSite/django_env' PYTHONPATH = (not set) Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' and when i go to my page i see and error 403: here is some more information about my files: (django_env) robch@django-server:~$ ls -la total 44 drwxr-x--- 6 robch robch 4096 Jun 27 01:44 . drwxr-xr-x 3 root root 4096 Jun 26 21:58 .. -rw------- 1 robch robch 1102 Jun 27 00:08 .bash_history -rw-r--r-- 1 robch robch 220 Jun 26 21:58 .bash_logout -rw-r--r-- 1 robch robch 3771 Jun 26 21:58 .bashrc drwx------ 3 robch robch 4096 Jun 26 23:45 .cache -rw------- 1 robch robch 20 Jun 27 01:44 .lesshst drwxrwxr-x … -
Integrate semgrep into reNgine
reNgine is your go-to web application reconnaissance suite that's designed to simplify and streamline the reconnaissance process for security professionals, penetration testers, and bug bounty hunters. And semgrep is a sast tool. I want to integrate semgrep into reNgine, here is the source code on github of both: https://github.com/semgrep/semgrep https://github.com/yogeshojha/rengine Does anyone have any ideas? I don't have any idea for this problem -
Django models - How to Aggregate Many-to-Many Related Objects into Arrays?
so I started working with Django recently, I'm having a case of many-to-many relationship between Book and Author -as simple example- a book could have multiple authors. class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField('Author', related_name='books') def __str__(self): return self.title class Author(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name My goal is to fetch the data of Book, but the problem is when a book has multiple authors, I get the same book row for each of its authors, the question is can I have a book row with all its authors stored in a list ? instead of a row for each author. Example of data fetching as JSON: [ { "id": 1, "title": "Good Omens", "authors__name": "Neil Gaiman" }, { "id": 1, "title": "Good Omens", "authors__name": "Terry Pratchett" }, { "id": 2, "title": "The Lord of the Rings", "authors__name": "J.R.R. Tolkien" } ] So I want something like this instead: { "id": 1, "title": "Good Omens", "authors__name": ["Neil Gaiman", "Terry Pratchett"] }, While it's easy to implement this via python code, I want a solution using model queries or ORM methods, to gain some performance and time since the data will be so big. The following code shows … -
How do I create an 'Update Profile Picture' function in django
Okay, so basically I created a function in django where you can change the profile picture but the issue is that It's doing something else instead. Have a look below to understand what's happening I have added these codes into my settings.py file settings.py STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') and also added these to the urls.py urls.py from django.contrib import admin from django.urls import path , include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('user/',include('members.urls')), path('',include('blogposts.urls')), # MAIN URL ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) This is the model that I created for the User models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE, null = True , blank = True ) bio = models.TextField() profile_pic = models.ImageField(upload_to = 'images',default= '/../media/images/image.png') def __str__(self): return str(self.user) This is the form that I created to change the Profile Pic forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['profile_pic'] This is the urls.py inside the app urls.py (app) from django.urls import path , include from . import views urlpatterns = [ path('',views.homepage,name = 'home-page'), path('view_post/<int:pk>',views.view_post,name='view-post'), path('blogcreation',views.create_blog,name='blog-form'), path('aboutme',views.about_user,name = 'show-user'), # this is the one that takes to the page … -
How to Properly Transform Backend Datafrom Django to Frontend Models in Angular
I am a beginner working on an Angular frontend with a Django backend. I have tried to formulate my question as precisely as possible. Please avoid downvoting; if anything is unclear, feel free to ask for clarification, and I will gladly provide more details. I have three models: Task, Subtask, and User. A Task can have multiple Subtasks. A Subtask belongs to exactly one Task. A Task can be handled by multiple Users. I receive the data tasks, subtasks, and users from the backend. A Subtask can only be created after the corresponding Task is created, as a Subtask must always have a taskId. Here are the most important data models: Backend: // Users { "id": 1, "email": "bob@bob.com", "name": "bob" } // Tasks { "id": 1, "title": "Task 1", "description": "Task 1", "due_to": "2024-06-26T13:18:08Z", "created": "2024-06-26T13:18:36.238944Z", "updated": "2024-06-26T13:18:36.239951Z", "priority": "LOW", "category": "TECHNICAL_TASK", "status": "TO_DO", "subtasks": [1], "users": [1] } // Subtasks { "id": 1, "task_id": 1, "description": "Subtask 1", "is_done": false } Frontend: In the frontend, I have a Task data structure which includes Subtasks and Users. export interface Task { id: number, title: string, description: string, dueTo: Date, created: Date, updated: Date, priority: Priority, category: Category, subtasks: Subtask[], … -
"manage.py runserver" now does not run with "py", only "python" overnight
Beginning with web development, using VSCode, Python 3.12.3 in a virtual environment, and Django 5.0.6. When running: py manage.py runserver I get: Unable to create process using 'c:\Users\MyUserName\Documents\GitHub\Coding Practice\Python\DjangoLearningMongo\.venv\Scripts\python.exe manage.py runserver' Another post suggested using just manage.py runserver, but that yields: Unable to create process using 'c:\Users\MyUserName\Documents\GitHub\Coding Practice\Python\DjangoLearningMongo\.venv\Scripts\python.exe "C:\Users\MyUserName\Documents\GitHub\Coding Practice\Python\DjangoLearningMongo\grocery_prices_mongo\manage.py" runserver' I have used py manage.py runserver for the entirety of the project just fine until this morning. Now, py fails to work with anything, yielding the above, and instead I must use python. These are the changes I made to the project yesterday: added static files to the project (static folder, settings.py to have STATIC_ROOT, py manage.py collectstatic, etc...) pip installed whitenoise to handle static CSS in production set DEBUG to FALSE Added 127.0.0.1 to ALLOWED_HOSTS I was still able to use py manage.py runserver (or other py manage.py commands) each step of the way as I made these changes, it was only this morning when I returned to the project that py stopped working and had to use python instead, which I had not needed to do at any point prior in the project. I even went to another project I have not run or edited in a … -
Django - Middleware losing connection with database on multi-tenant app
On my Django app I use a multi-tenant approach with isolated databases. It works well but because it relies on subdomains for each tenant, which is not scalable, I'm trying to change that. To achieve this functionality I'm trying to use middlewares and sessions to retrieve the tenant from the username and use it to set a local variable for the database routers. The logic is this: If the user is not logged, the BeforeLoginMiddleware activates and retrieves the tenant name from the user. So username@tenant1 will set tenant1 to the session. Here's the code: import threading from users.forms import LoginForm Thread_Local = threading.local() class BeforeLoginMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path == '/login/': form = LoginForm(request.POST) if form.is_valid(): complete_username = form.cleaned_data.get('username') current_db = complete_username.split('@')[1] request.session['current_db'] = current_db request.session.modified = True response = self.get_response(request) return response If the user is already logged, a second middleware will retrieve the tenant data from the session and use it to define the Thread_Local variable that is called on a function used on the database routers: class AppMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): current_db = request.session.get('current_db') setattr(Thread_Local, 'current_db', current_db) response = self.get_response(request) return response def … -
Tox+Django can't find package after Django upgrade
I recently upgraded my Django dependency to 4.2, and now running tests via Tox fails with: ModuleNotFoundError: No module named 'mypackage' I haven't changed anything else and running Tox for Django 3.2 works fine. My tox.ini looks like: [tox] envlist = py{38}-django{32,42} recreate = True [testenv] basepython = py38: python3.8 deps = -r{toxinidir}/requirements.txt -r{toxinidir}/requirements-test.txt django32: Django>=3.2,<3.3 django42: Django>=4.2,<5.0 -e . # Install the current package in editable mode commands = django-admin.py test --traceback --settings=mypackage.tests.settings mypackage.tests.tests.TestCase and my project structure looks like: myproject/ ├── myproject/ │ ├── __init__.py │ ├── tests/ │ │ ├── __init__.py │ │ ├── settings.py │ │ └── tests.py │ └── ... ├── .tox/ ├── .env/ ├── .git/ ├── setup.py ├── requirements.txt ├── requirements-test.txt ├── tox.ini └── ... and my test settings look like: import os PROJECT_DIR = os.path.dirname(__file__) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } ROOT_URLCONF = 'mypackage.tests.urls' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'mypackage', 'mypackage.tests', 'admin_steroids', ] MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') USE_TZ = True TIME_ZONE = 'America/New_York' USE_DEPRECATED_PYTZ = True AUTH_USER_MODEL = 'auth.User' SECRET_KEY = 'abc123' SITE_ID = 1 BASE_SECURE_URL = 'https://localhost' BASE_URL = 'http://localhost' MIDDLEWARE_CLASSES = MIDDLEWARE = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', ) TEMPLATES …