Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POO (Python w/Django) [closed]
Bonjour, bonsoir, Je vous demande votre aide afin de comprendre le principe et comment faire de la Programmation Orienté Objet, je suis actuellement en formation de Développeur Web & Web Mobile, et j'apprends actuellement la POO mais en regardant des vidéos diverses pour comprendre, et même avec les cours je n'arrive pas à comprendre le fonctionnement, (Je n'ai pas eu d'exercice sur ça, j'ai directement eu un devoir), pourrais-vous me montrer un exemple de POO avec une "Description" ou des détails svp. PS : Mon devoir est sur une application bibliothécaire à remettre aux gouts du jour. Voici à quoi il ressemble. def menu(): print("menu") if name == 'main': menu() class livre(): name = "" auteur = "" dateEmprunt = "" disponible = "" emprunteur = "" class dvd(): name = "" realisateur = "" dateEmprunt = "" disponible = "" emprunteur = "" class cd(): name = "" artiste = "" dateEmprunt = "" disponible = "" emprunteur = "" class jeuDePlateau : name = "" createur = "" class Emprunteur(): name = "" bloque = "" def menuBibliotheque() : print("c'est le menu de l'application des bibliothéquaire") def menuMembre(): print("c'est le menu de l'application des membres") print("affiche tout") Comprendre, … -
Django: Vendor Dashboard Not Displaying All Orders for Products Sold
I'm working on a Django project where I have a vendor dashboard that should display all orders for the products uploaded by the current vendor. However, the dashboard is only showing orders placed by one user and not orders placed by other users for the same products. Models: Here are the relevant models: class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=RichTextUploadingField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=RichTextUploadingField(null=True, blank=True) tags=TaggableManager(blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price def get_product_price_by_size(self , Size): return self.price + Size.objects.get(name = Size).price class CartOrder(models.Model): user=models.ForeignKey(CustomUser,on_delete=models.CASCADE) item=models.CharField(max_length=100) price= models.DecimalField(max_digits=10, decimal_places=2,default="1.99") paid_status=models.BooleanField(default=False) order_date=models.DateTimeField(auto_now_add=True) product_status=models.CharField(choices=STATUS_CHOICE, max_length=30,default="processing") class Meta: verbose_name_plural="Cart Order" class CartOrderItems(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE,default=1) #I have to fix the default order=models.ForeignKey(CartOrder,on_delete=models.CASCADE,related_name="cartorderitems") # product = models.ForeignKey(Product, on_delete=models.CASCADE, default=1) invoice_num = models.BigIntegerField(blank=True,null=True) product_status=models.CharField(max_length=200) item=models.CharField(max_length=100) image=models.CharField(max_length=100) qty=models.BigIntegerField(default=0) price= models.DecimalField(max_digits=12, decimal_places=2,default="15") total= models.DecimalField(max_digits=12, decimal_places=2,default="20") color=models.ForeignKey(Color,on_delete=models.SET_NULL,null=True,blank=True) size=models.ForeignKey(Size,on_delete=models.SET_NULL,null=True,blank=True) class Meta: verbose_name_plural="Cart Order Items" def catagory_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def oder_img(self): return mark_safe('<img src="/media/%s" width="50" height="50"/>'%(self.image)) View: Here is the view … -
How to mark a DRF ViewSet action as being exempt from the application of a custom middleware?
I've created a Custom Django Middleware and added to the MIDDLEWARE settings variable correctly. from django.http import HttpResponseForbidden class MyCustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): # Perform some internal actions on the `request` object. return None Since this is applied to all DRF ViewSets by default, I would like to exempt some actions that don't need this check. The idea would be to check a flag inside the process_view function taking inspiration from the Django CsrfViewMiddleware which checks if the csrf_exempt variable has been set by the csrf_exempt decorator. So I modified the custom middleware and created a custom decorator to exempt views explicitly. from functools import wraps from django.http import HttpResponseForbidden class MyCustomMiddleware: ... def process_view(self, request, view_func, view_args, view_kwargs): if getattr(view_func, "some_condition", False): return HttpResponseForbidden("Forbidden on custom middleware") # Perform some internal actions on the `request` object. return None def custom_middleware_exempt(view_func): @wraps(view_func) def _view_wrapper(request, *args, **kwargs): return view_func(request, *args, **kwargs) _view_wrapper.some_condition = True return _view_wrapper Having this I do something like this and it correctly enters the custom decorator before going inside the Django middleware. from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import … -
Django return "You are not allowed to perform this action." when creating a new entry
I have an application which i want to run scripts. Those scripts are stored in a database. This is how i do all of this using Django 5.0.1 : First of all, this is my settings file : #... INSTALLED_APPS = [ # Django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My apps 'personal', ] 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', ] #... This is my urls file : from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), #... ] This is my models file : from django.db import models from django.core.exceptions import ValidationError from django.conf import settings from os.path import join class Product(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=True) def __str__(self): return self.name class Type(models.Model): short_name = models.CharField(max_length=3, null=False, blank=False, unique=True) complete_name = models.CharField(max_length=30, null=False, blank=False) def __str__(self): return self.complete_name class Version(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) version = models.CharField(max_length=30, null=False, blank=False) constraints = [ models.UniqueConstraint(fields=['product', 'version'], name='unique_product_version'), ] def __str__(self): return f"{self.product} {self.version}" class TypeTestRelation(models.Model): type = models.ForeignKey(Type, null=False, blank=False, related_name='attributed_tests', on_delete=models.CASCADE) test = models.ForeignKey(Test, null=False, blank=False, on_delete=models.CASCADE) class Meta: unique_together = ['type', 'test'] class Test(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=True) file = models.FileField(upload_to=join(join(settings.BASE_DIR, "static"), "scripts"), null=True, blank=False) # Add the file field … -
Django pet-project for beginners [closed]
I start to study django and have no idea what do i can write most useful for practicing this in the beginning. Could anyone give some advices for choosing theme for my unboarn projectc? Maybe blog or onlain-shop, Idk.. Thanks! I try to write one site with using db SQLite, auth, admin panel, models, some simple model etc. This is my start background -
What is the fastest way to query for items with an existing foreign key and many-to-many entry in Django?
I have a simple model with a foreign key and a many-to-many relationship: class Car(models.Model): uuid = models.UUIDField() is_red = models.BooleanField() class Owner(models.Model): car = models.ForeignKey(Car, to_field="uuid", on_delete=models.CASCADE) class Driver(models.Model): cars = models.ManyToManyField(ProtectedArea, related_name="cars") Now a lot of my application logic relies on cars on which at least one of the three conditions: it is red, it has at least one owner, it has at least one driver is true. It might be an important information, that in reality the Car-model contains some rather big polygonal data, maybe that is relevant for performance here? I have a custom manager for this but now matter how I built the query it seems extremely slow. Times are taken from my local dev machine with ~50k cars, 20k Owners, 1.2k Drivers. The view is a default FilterView from django-filter without any filters being actually active. My manager currently looks like this: class ActiveCarManager(models.Manager): def get_queryset(self): cars_with_owners = Owner.objects.values("car__uuid").distinct() cars_with_drivers = Drivers.objects.values("cars__uuid").distinct() return ( super() .get_queryset() .filter( Q(uuid__in=cars_with_owners) | Q(uuid__in=cars_with_drivers) | Q(is_red=True) ) ) The view generates 2 queries from this, one count query and one query to fetch the actual items. The query that is so slow is the count query. On our … -
get the lastest record of an object
I have two models: Cat (id, name) CatRecords (id, cat_id, status, created_time) Each day, a cat have one record about the status of the cat I want to get all the cats and the latest record of each, sorted by the created_time of the record I can get all records of each cat, but I cannot get the latest record of each The query class of Cat: class Query(graphene.ObjectType): all_cats = graphene.List(CatType) cat = graphene.Field(CatType, cat_id=graphene.UUID()) latest_record = graphene.Field(CatRecordType) def resolve_all_cats(self, info, **kwargs): cats = Cat.objects.all() return cats def resolve_cat(self, info, cat_id): return Cat.objects.get(cat_id=cat_id) def resolve_latest_record(self, info): subquery = CatRecord.objects.filter(cat_id=OuterRef("id")).order_by( "-created_time" ) return ( Cat.objects.all() .annotate(latest_record=Subquery(subquery.values("id")[:1])) .values("latest_record") ) My query query { latestRecord{ id name } } the error is { "errors": [ { "message": "Received incompatible instance \"<QuerySet [{'latest_record': UUID('3d2af716-94aa-4952-9050-4d7f69384e3d')}, {'latest_record': UUID('0705aeda-a2ec-47c3-8bd1-1aa445c40444')}]>\".", "locations": [ { "line": 2, "column": 3 } ], "path": [ "latestRecord" ] } ], "data": { "latestRecord": null } } -
Django Social Authentication Issue: Unable to Login Using Facebook or LinkedIn
I'm facing an issue with integrating social authentication (Google, Facebook, LinkedIn) into my Django web application using social-auth-app-django. While Google login works fine, I'm unable to get Facebook or LinkedIn login to function correctly. Login | Facebook Error | Linkedin Error | Linkedin Error2 I followed the setup instructions for social-auth-app-django and configured the keys and secrets for Google, Facebook, and LinkedIn in my settings.py. Google authentication works as expected, redirecting users to the correct page after login. However, when attempting to log in using Facebook or LinkedIn, the authentication process fails silently without any clear error message or redirection.Steps Taken: Verified client IDs and secrets for Facebook and LinkedIn are correctly set in settings.py. Ensured correct scopes and field selectors are configured for LinkedIn. Checked that all necessary middleware and context processors are included in settings.py. from pathlib import Path import os import logging BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-@*#c*5am%k5_-@#axxxxxxxxxxxah=(h9pbnf!z-x01h@n#66' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'demo', 'social_django', ] 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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'signin.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
how change the MARKDOWNX_MEDIA_PATH in Django setting to include the image name in the path?
I am using the markdown library, i want to change the path to the images in a way that it contains the name of the file, according to the markdown [doc][1] the path can change by adding something like : from datetime import datetime MARKDOWNX_MEDIA_PATH = datetime.now().strftime("markdownx/%Y/%m/%d") i tried adding image.name but it didn't work in the setting now i was wondering if i can inject the file name here in the setting some how? -
django-admin startproject coredj File "<stdin>", line 1 django-admin startproject core SyntaxError: invalid syntax what's problem here?
whenever i am firing django-admin startproject core this command it throws me syntax error. iam using python version3.11 and django version in 5.0.6. iam trying to create this in my E:drive and i have succesfullly installed the django and import it look for the version created virtaul env but still,not working throwing syntax error at startproject django-admin startproject coredj File "", line 1 django-admin startproject coredj ^^^^^^^^^^^^ SyntaxError: invalid syntax i checked for compatible version of django with python.when i run the command i expect it to create the foldername core in my pythonproject directory which is residing in my** E :**but it's not happening -
In django by turn off the button edit the value in database to ‘NO’ on turn on the button change it to ‘YES’. Using Django
models.py class AssetOwnerPrivileges(models.Model): asset_add = models.CharField(max_length=20,default='YES') html button <td> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </td> When button switch "ON" ,value in database change to YES ,while button switch "OFF" value change to "NO". -
How to send user ID through forms
I want to display the information in the profile section after receiving the information from the user But I can't submit the user ID through the forms My Models: class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='information') full_name = models.CharField(max_length=40) email = models.EmailField(blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name My Forms: class PersonalInformationForm(forms.ModelForm): user = forms.IntegerField(required=False) class Meta: model = PersonalInformation fields = "__all__" MY Views: class PersonalInformationView(View): def post(self, request): form = PersonalInformationForm(request.POST) if form.is_valid(): personal = form.save(commit=False) personal.user = request.user personal.save() return redirect('profile:profile') return render(request, 'profil/profile-personal-info.html', {'information': form}) def get(self, request): form = PersonalInformationForm(request.POST) return render(request, 'profil/profile-personal-info.html', {'information': form}) -
Is serializer.save() atomic?
@api_view(["POST"]) def register_view(request: "Request"): serializer = RegisterSerializer(data=request.data) serializer.is_valid(raise_exception=True) try: serializer.save() except IntegrityError: raise ConflictException return Response(serializer.data, status=status.HTTP_201_CREATED) class ConflictException(APIException): status_code = 409 default_detail = "username is already taken" default_code = "conflict" def test_username_taken(self): with transaction.atomic(): User.objects.create_user(username="customer4", password="Passw0rd!") response = self.client.post( "/register", { "username": "customer4", "password": "Passw0rd!", "confirm_password": "Passw0rd!", "phone_number": "13324252666" }, ) self.assertEqual(response.status_code, status.HTTP_409_CONFLICT) The test result shows : raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I'm a Django and DRF noob and don't know what to do... I tested on postman and there is no problem, with 409 status_code response -
Is it possible to use transfer my django app on fme
So I created a randomiser app with django, I used import random and just called the function in my views. I could also use an implementation of fisher-yates algo to implement the randomisation I want. The person I built the app for has no python knowledge. They can't code with python. So I am trying to maybe integrate the python code on FME because they are efficient in using that. I was just wondering if it will be possible for me to do that. Has anyone tried something like that before and successfully done it. I am taking a short course in FME right now just to learnt the basics of using it. I am just wondering if there are any courses you guys will recommend or any steps for be to integrate the app on FME so they don't have to use django to use the app. -
What is causing this BadDeviceToken response in APNS?
This is my code sending the apns: @classmethod def PingDevice(cls, devicetoken, pushmagic): # Create the payload for the push notification payload = Payload(custom={'mdm': pushmagic}) print("Payload:", payload) print(f"device token: {devicetoken}") # Path to your certificate cert_path = os.path.join(settings.BASE_DIR, 'sign', "PushCert.pem") print("Certificate Path:", cert_path) # Load your certificate and private key credentials = CertificateCredentials(cert_path) print("Credentials:", credentials) # Create an APNs client apns_client = APNsClient(credentials=credentials, use_sandbox=False) print("APNs Client:", apns_client) # Send the push notification try: response = apns_client.send_notification(token_hex=devicetoken, notification=payload, topic='apns-topic') if response == 'Success': print("Push notification sent successfully") else: print(f"Failed to send notification: {response.description}") except Exception as e: print('Bad device token:', e) But i face the problem this is response i get with print in code on AWS: Bad device token: I really appreciate any help. -
OIDC Linkedin authentication canceled in django applicaation
I have integrated OIDC Linkedin third party auth in my django application and it automatically cancled authenticaton. I'm attaching logs for refrence, if anyone faced this issue before or does anyone know the solution please feel free to give me soluction, logs Django version is 4.1.2 library i used social-auth-core: 4.5.4 -
Dynamically generate django .filter() query with various attrs and matching types
I use django 1.6 (yep, sorry) and python2.7 and I need to generate queryset filter dynamically. So, the basic thing I need is to use different fields (field1, field2, field3) in filter and use different type of matching (equals, startsfrom, endswith, contains). Here as an example of possible combinations: Mymodel.objects.filter(field1__strartswith=somevalue). # Or like this: Mymodel.objects.filter(field2__endswith=somevalue). # Or like this: Mymodel.objects.filter(field3=somevalue) # Or like this: Mymodel.objects.filter(atrr3__contains=somevalue) I've found this answer and it looks good but I believe there are some more "django-like" ways to do it. I've also found this one with Q object. But maybe I can somehow import and pass to the queryset some objects of this types of matching? -
How can I get an image displayed in HTML with the URL from a context-object?
I'm new to Django and I'm now stuck at a problem of getting an image from a database displayed in an HTMl via it's URL. I had a code that was already working and I now tried to add advanced features and that's were all started to fall apart. So first of all what's already working: I have a Database where I store the URLs of Images and other data. I then display the images and the other data in a "Report"-Template. This is my view.py for this: from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from .utils import get_report_image from .models import Report1 from django.views.generic import ListView, DetailView from django.conf import settings from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa import pandas as pd class ReportListView(ListView): model = Report1 template_name = 'reports/main.html' class ReportDetailView(DetailView): model = Report1 template_name = 'reports/detail.html' # Create your views here. def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def create_report_view(request): if is_ajax(request): report_id = request.POST.get('report_id') name = request.POST.get('name') remarks = request.POST.get('remarks') img_Energie = request.POST.get('img_Energie') img_Emissionen = request.POST.get('img_Emissionen') img_Energie = get_report_image(img_Energie) img_Emissionen = get_report_image(img_Emissionen) #print("report_id: ", report_id) Report1.objects.create(report_id = report_id, name=name, remarks=remarks, image_Energie=img_Energie, image_Emissionen=img_Emissionen) return JsonResponse({'msg': 'send'}) return JsonResponse({}) and this is … -
static url settings in jinja2
I'm using jinja2 template in Djagon and I want to assign a static url for all my project so that I won't use long relative path in my css and js file. Below is how I set jinja2 template in Django and configured jinja2 environment. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'environment': 'project.utils.jinja2_env.jinja2_environment', }, }, ] def jinja2_environment(**options): """ This is the :param options: :return: """ env = Environment(**options) env.globals.update({ 'static': StaticFilesStorage.url, 'url': reverse, }) return env However, when I use the static url in my css or js like: <link rel="stylesheet" type="text/css" href="{{ static('css/reset.css') }}"> It raised an error like: File "***\login.html", line 6, in top-level template code <link rel="stylesheet" type="text/css" href="{{ static('css/reset.css') }}"> TypeError: FileSystemStorage.url() missing 1 required positional argument: 'name' I guess maybe there is some conflict between jinja2 and Django because I can't use Django template suggested like below neither {% load static %} {% static 'css/reset.css' %} I could not figure this out. Someone could help me here? Thanks. -
Django creating duplicate records
There are only 5 subjects in the Subject table with unique names, but when run the following query to fill the table, some students have 5 some 10 and some are populated with 15 or 20 records. It should create records for every student for every subject only once. Any clue? def create_student_marks()-> None: try: students_obj = Student.objects.all() for student in students_obj: subjects_obj = Subject.objects.all() for subject in subjects_obj: SubjectMarks.objects.create( student = student, subject = subject, marks = random.randint(30, 100) ) except Exception as ex: print(ex) -
gunicorn issues with ModuleNotFoundError when deploying DRF project to Render due to
DRF project is running in development environment, expects to deploy to Render through yaml. The error message is as follows: ==> Running 'gunicorn core.wsgi:application' Traceback (most recent call last): File "/opt/render/project/src/.venv/bin/gunicorn", line 8, in <module> sys.exit(run()) ^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 67, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]", prog=prog).run() File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/base.py", line 236, in run super().run() File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() ^^^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/arbiter.py", line 58, in __init__ self.setup(app) File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/arbiter.py", line 118, in setup self.app.wsgi() File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() ^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() ^^^^^^^^^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/util.py", line 371, in import_app mod = importlib.import_module(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'core' gunicorn is called in Procfile as follows: web: gunicorn core.wsgi:application have tried to change the module name to django_project.core.wsgi:application but the … -
Django __main__.Profile doesn't declare an explicit app label
So I am working on Django and have not much experience with it yet. So far I've set up alright but now I've run into this error: RuntimeError: Model class main.Profile doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The INSTALLED_APPS looks like INSTALLED_APPS = [ 'tweets.apps.tweetsConfig', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'de Sitter vacua', ] I'm completely flabbergasted at this because I have no idea what the issue here is. I tried going through stackexchange Q&As and am clueless as to what the issue here is. Tried some solutions but it doesn't seem to be working. -
Coolify Django Deployment
I'm using Coolify and I want to deploy a Django application. I created an entrypoint.sh #!/bin/sh set -e echo "Running migrations..." python manage.py migrate echo "Collecting static files..." python manage.py collectstatic --noinput echo "Starting Gunicorn HTTP server..." exec gunicorn coolify.wsgi:application --bind 0.0.0.0:8000 I have a Dockerfile and it's all connected in a docker-compose.yml file with the db. The containers are running but I keep getting a Bad Request 400 response for any endpoint. -
Using jquery-editable-select in a Django App
This is my very first Django app so please don't be too harsh :-) I'm trying to use jquery-editable-select in my Django web App but I'm lost. https://github.com/indrimuska/jquery-editable-select According to this link, it seems like I need to install NPM first or Bower. I don't know what these are, can someone give me the basics from scratch ? Is it something to install via PIP like a python package ? -
What percentage of production backends use Raw SQL directly? [closed]
I was looking at Tech Empower’s web frameworks benchmarks.. I noticed that the highest performing versions of the frameworks used raw sql and the setups of the same frameworks that used an ORM or Query builder were significantly less performant (up to 5 times!). Look at actix-web, axum for example. So i’d like to know in a real, large big tech, production environment is raw SQL used and never ORMs or Query builders?