Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post data along with photo to django rest with requests package
I wrote an api with django rest and I want to post data and photo with requests package. When I want to send data like this -> data = { 'name':'data', 'price':'123', 'category':1 } everything works correctly and the data is saved in the database, but when I want to send a photo along with the data, I get an error. models.py class Menu(models.Model): image = models.ImageField(upload_to="img", blank=True, null=True) name = models.CharField(max_length=100) price = models.IntegerField() category = models.IntegerField() availability = models.BooleanField(default=False) serializers.py class MenuSerializer(serializers.ModelSerializer): class Meta: model = Menu fields = ('id', 'image', 'name', 'price', 'category','availability') views.py class MenuViewset(ListCreateAPIView): queryset = Menu.objects.all() serializer_class = MenuSerializer and this is my post request with the requests package that I wrote in PyQt: class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__() url = 'http://127.0.0.1:8000/api/upload/' headers = {'Content-Type': 'multipart/form-data'} data = {'image':('chat2.png', open('chat2.png','rb'),"multipart/form-data"), 'name':'data', 'price':'123', 'category':1 } r = requests.post(url, data=data , headers=headers) if __name__ == '__main__': app = QApplication([]) window = MainWindow() app.exec_() -
i am getting server error while calling post method in my api using batch file
I am getting right result using both methods when i running my manage.py script through pycharm, but when i am running it through batch file, then i am getting server error 500 for post method. This is my batch file- @echo off cd F:/hash/hashtaggenerator/ set "VIRTUAL_ENV=F:\hash\env" if defined _OLD_VIRTUAL_PROMPT ( set "PROMPT=%_OLD_VIRTUAL_PROMPT%" ) else ( if not defined PROMPT ( set "PROMPT=$P$G" ) if not defined VIRTUAL_ENV_DISABLE_PROMPT ( set "_OLD_VIRTUAL_PROMPT=%PROMPT%" ) ) if not defined VIRTUAL_ENV_DISABLE_PROMPT ( if "" NEQ "" ( set "PROMPT=() %PROMPT%" ) else ( for %%d in ("%VIRTUAL_ENV%") do set "PROMPT=(%%~nxd) %PROMPT%" ) ) REM Don't use () to avoid problems with them in %PATH% if defined _OLD_VIRTUAL_PYTHONHOME goto ENDIFVHOME set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%" :ENDIFVHOME set PYTHONHOME= REM if defined _OLD_VIRTUAL_PATH ( if not defined _OLD_VIRTUAL_PATH goto ENDIFVPATH1 set "PATH=%_OLD_VIRTUAL_PATH%" :ENDIFVPATH1 REM ) else ( if defined _OLD_VIRTUAL_PATH goto ENDIFVPATH2 set "_OLD_VIRTUAL_PATH=%PATH%" :ENDIFVPATH2 set "PATH=%VIRTUAL_ENV%\Scripts;%PATH%" F:/hash/env/Scripts/python.exe manage.py runserver ip address:4321 pause -
DRF: API root view doesn't list my APIs for some reasons
I have the following urls.py for an app named service where I register API endpoints: from .views import AccessViewSet, CheckViewSet app_name = "api" router = DefaultRouter() router.register(r"access/(?P<endpoint>.+)", AccessViewSet, basename="access") router.register(r"check/(?P<endpoint>.+)", CheckViewSet, basename="check") urlpatterns = [ path("", include(router.urls)), ] Below is my project's urls.py where I use it: from django.conf import settings from django.contrib import admin from django.urls import include, path from django.views.generic import RedirectView import service.urls as service_urls urlpatterns = [ path("service/", include('service.urls')), ] The APIs themselves work fine, but I cannot make them work with the DRF's default API root view. It shows an empty list of available endpoints. How do I fix this? I am not sure, but maybe it is somehow related to the regular expressions I use while registering endpoints, i.e.: r"access/(?P<endpoint>.+)". If that's the issue, then how do I go about dealing with such cases? -
django_migrations table in DB causing ValueError: Not naive datetime (tzinfo is already set)
I did lot's of try, catch on this issue and basically still not find the core problem but this is what I got for now. in the settings.py I am turning on the USE_TZ = True TIME_ZONE = 'UTC' and creating a model like below. class Plan(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=100) price = models.IntegerField() description = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name when I try to makemigration for this is no problem. Here is the first migration file of Plan model class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Plan', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('code', models.CharField(max_length=100)), ('price', models.IntegerField()), ('description', models.TextField(blank=True, null=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), ] Now, when I try to migrate this file. There are two table created in the DB. one for django_migrations and the other is Plan model. After running migrate command. error follows. raise ValueError('Not naive datetime (tzinfo is already set)') ValueError: Not naive datetime (tzinfo is already set) first plan model causing this error. But when I delete the django_migrations table from DB. error not recurring. any idea why django_migrations causing not naive datetime error? Additionally. … -
Integrity error while running migrate to add new column in Django
Having a table that has millions of records, and wants to add a new column to that table in Django, so while running migrate, it is taking time (due to huge data) but getting failed after sometime with Error django.db.utils.IntegrityError: (1062, "Duplicate entry '2287526-softwareengineer' for key 'api_experience_entity_id_585e67e2a704aaa3_uniq'") Though the entity_id(2287526) has no duplicate entries, but i could see that this entry was updated during the time migration was running. what could be the possible solution to perform migration without affecting data and near to no downtime for system? SHOW CREATE TABLE api_experience; CREATE TABLE api_experience(idint(11) NOT NULL AUTO_INCREMENT,typevarchar(100) NOT NULL,durationvarchar(200) NOT NULL,created_atdatetime NOT NULL,updated_atdatetime NOT NULL,entity_idint(11) NOT NULL,designation varchar(100), PRIMARY KEY (id), UNIQUE KEY api_experience_entity_id_585e67e2a704aaa3_uniq (entity_id,type), KEY api_experience_599dcce2 (type), KEY api_experience_5527459a (designation), KEY api_experience_created_at_447d412d906baea1_uniq (created_at), CONSTRAINT api_entity_id_3fbe8eb2deb42063_fk_api_entity_id FOREIGN KEY (entity_id) REFERENCES api_entity (id`) ) ENGINE=InnoDB AUTO_INCREMENT=773570676 DEFAULT CHARSET=utf8 ` Have tried with running migration in low traffic in midnight but didn't help. -
Create dashboard for django 5xx errors
I want to build a dashboard for watching and tracing 5xx errors. So I need something constructed specially for this. I'm using Kibana to access my log which not contains 5xx errors. So what can I do? -
I need django inline dynamic
Basically I have this screen and according to the value selected in “metodo_pagamento” I want to display the amount of inline form, example if I select “2 Parcelas”, it shows 2 forms inline, but I wanted to do this dynamically how do I do that too to update and delete?formlike this: In this way that i did in using javascript onchange, but its dificult make update when user select other “Metodo pagamento”, anyone can help me? -
How to access uploaded images via URL in Django?
I'm building a simple blog style web app for a friend. I am using CK editor and mostly stock Django 4.1. I'm stumped in how in what would be the best approach to let the creator to upload and serve images in their posts. CK editor allows you to add images via URL and I'd like for it to be possible to the creator to upload their files to the backend and would like to know if there are best practices when it comes to this. Right now I have this: def editor_upload(request): if request.method == 'GET': form = UploadFileForm path = os.path.join(settings.STATIC_ROOT, 'files') files = os.listdir(path) return render(request, 'upload.html', {"form": form, "files": files}) if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) file = request.FILES['file'] title = str(file) if form.is_valid(): path = os.path.join(settings.STATIC_ROOT, 'files') fs = FileSystemStorage(location=path) fs.save(title, file) return redirect('/editor/upload') def open_file(request, file_name): print(file_name) return render(request, 'file.html', {"file": file_name}) in editor_upload, the user can see what files there are in the specified folder (but cannot access them yet) and there is the logic to upload new pictures to the folder. The problem comes now: I don't know how to properly access them. In open_file, the request receives the name … -
Django error trying to insert number from forms into Sqlite
I'm getting this error Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: Sistema_receita.value while trying to receive a number from this form <div class="mb-3"> <label for="dataReceita" class="form-label">Data</label> <input type="date" class="form-control" id="dataReceita" aria-describedby="dataReceita" value=""> </div> into this view def cadastrar_receita(request): if request.method == 'POST': receita = Receita() receita.date = request.POST.get('dataReceita') receita.value = request.POST.get('valorReceita') receita.professional = request.POST.get('profissionalReceita') receita.desc = request.POST.get('descricaoReceita') receita.pago = request.POST.get('pagoReceita') receita.save() and this is my model class Receita(models.Model): date = models.DateTimeField(auto_now_add=True) value = models.DecimalField(max_digits=12,decimal_places=2) professional = models.CharField(max_length=100, blank=True, null=True) desc = models.CharField(max_length=300, blank=True, null=True) pago = models.BooleanField(default=False, blank=True, null=True) I've tried using localize=True like this value = models.DecimalField(max_digits=12,decimal_places=2, localize=True) but it just gives me another error, and it doesn't matter whether I write a number like this 185,35 or 185.35, both gives me the same error I've tried using localize=True but it didn't help me -
Monkey patch disabled Sentry logging
I'm working on a Django project with Sentry attached for error logging. I want to log all outgoing HTTP requests made, so I wrote a monkey patch that modifies Python's http module. The idea was to modify the lowest level module possible so that all requests made by higher level libraries (urllib3, requests, and SDKs that use those libraries) would also be logged. Here is the patch code: def httpclient_logging_patch(): # NEEDS WORK: turning on this patch unexpectedly disables Sentry reporting. request = http.client.HTTPConnection.request getresponse = http.client.HTTPConnection.getresponse def patched_request(self, *args, **kwargs): try: method, url, body = args[:3] except ValueError: method, url = args[:2] body = kwargs.get("body") try: body = body.decode() except AttributeError: pass url_pieces = url.split("?") req_url = url_pieces[0] params = "?".join(url_pieces[1:]) stack = traceback.extract_stack() reduced_stack = traceback.StackSummary.from_list( [f for f in stack if "/venv/" not in f.filename] ) self.timestamp = datetime.datetime.utcnow() self._reporting_metadata = { "datetime": self.timestamp.strftime("%Y-%m-%dT%H:%M:%S.%f"), "request_id": str(uuid.uuid4()), "host_name": self.host, "req_url": req_url, "method": method, "req_body": body or "", "req_parameters": params or "", "context": "".join(reduced_stack.format()), } request(self, *args, **kwargs) def patched_getresponse(self, *args, **kwargs): response = getresponse(self) latency = int((datetime.datetime.utcnow() - self.timestamp).total_seconds() * 1000) reporting_metadata = { **self._reporting_metadata, "res_code": response.code, "success": response.code < 400, "latency": latency, "res_body": "", } if settings.ENVIRONMENT … -
react-social-login How to send token facebook to django-graphql to register new user?
i have a prooject developed in django and graphene library my code in schema.py is follow: import graphene from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType from graphql import GraphQLError from .models import Profile from django.contrib.auth import get_user_model, authenticate, login as auth_login from django.utils.translation import gettext_lazy as _ from django.http import HttpRequest from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from allauth.socialaccount.providers.facebook.provider import FacebookProvider from allauth.socialaccount.models import SocialApp from graphql_jwt.shortcuts import get_token from .types import UserType class RegisterSocialMutation(graphene.Mutation): """ Mutation to handle social registration """ token = graphene.String() user = graphene.Field(UserType) class Arguments: accessToken = graphene.String(required=True) def mutate(self, info, accessToken): User = get_user_model() try: # Use allauth to complete the social registration app = SocialApp.objects.get(provider="facebook") request = HttpRequest() request.POST = {'access_token': access_token} request.user = AnonymousUser() adapter = + user = adapter.complete_login(request, app, None) # Login the user auth_login(request, user) # Issue JWT token for the user token = get_token(user) return RegisterSocialMutation(token=token, user=user) except Exception as e: raise GraphQLError(str(e)) class ProfileType(DjangoObjectType): class Meta: model = Profile class Query(graphene.ObjectType): profile = graphene.Field(ProfileType) def resolve_profile(self, info): user = info.context.user if user.is_anonymous: raise Exception(_('You must be logged in to see your profile')) return Profile.objects.get(user=user) class Mutation(graphene.ObjectType): register_social = RegisterSocialMutation.Field() on my file types.py import graphene from django.contrib.auth import … -
MySql database is read-only and I can't change it
I am creating an app in Django using MySql and AWS RDS to handle my database, but when I called form.save() to save my new model to the database, I got this error: OperationalError at /plan/create/ attempt to write a readonly database This is my settings.py: """ Django settings for travelApp project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CSRF_COOKIE_HTTPONLY = True # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'i1kf*^g1+dt*8n9bgcl80$d!970186x(x(9z2)7dfy1ynlxixn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['travelApp-kool4-env.eba-pfvej56m.us-west-2.elasticbeanstalk.com', "52.27.98.222", "35.166.8.118", "127.0.0.1",] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'crispy_forms', 'django.contrib.staticfiles', 'sights.apps.SightsConfig', 'itineraries.apps.ItinerariesConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'travelApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'static')], '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', ], }, }, ] TEMPLATE_DIRS = ( '/home/django/myproject/templates', ) … -
Passing CHOICES to as an ID to template
As you can see the photo above, I have displayed all "CATEGORY_CHOICES" (in forms of (Groceries, Groceries) in category.html. views.py def category(request): context = {'CATEGORY_CHOICES': Category.CATEGORY_CHOICES} return render(request, 'category.html', context) def view_category(request, category_id): category = Category.objects.get(category_id=category_id) return render(request, 'view_category.html', {'category':category}) models.py class Category(models.Model): CATEGORY_CHOICES = [ ('Groceries', 'Groceries'), ('Salary', 'Salary'), ('Bills', 'Bills'), ('Rent', 'Rent'), ('Gym', 'Gym'), ('Restaurant', 'Restaurant'), ('Vacation', 'Vacation'), ('Travel', 'Travel'), ('Gift', 'Gift'), ('Investments', 'Investments'), ('Savings', 'Savings'), ('Entertainment', 'Entertainment'), ('Internet', 'Internet'), ('Healthcare', 'Healthcare'), ('Lifestyle', 'Lifestyle'), ('Insurance', 'Insurance'), ('Other', 'Other'), ] category_choices = models.CharField(max_length=50, blank=False, choices=CATEGORY_CHOICES) budget = models.DecimalField(max_digits=10, decimal_places=2) start_date = models.DateField(blank=False) end_date = models.DateField(blank=False) spending_limit = models.DecimalField(max_digits=10, decimal_places=2) category.html {% extends 'base_content.html' %} {% block content %} <div class="container"> <div class="row justify-content-center"> <div class="row" style="width:90%"> <div class="col-sm-4 text-center my-3"> <div class="card card-block" style="height : 300px"> <div class="card-body align-items-center d-flex justify-content-center"> <h5 class="card-title">Overall</h5> <a href="" class="stretched-link"></a> </div> </div> </div> {% for item in CATEGORY_CHOICES %} <div class="col-sm-4 text-center my-3"> <div class="card card-block" style="height : 300px"> <div class="card-body align-items-center d-flex justify-content-center"> <h5 class="card-title">{{ item.1 }}</h5> <a href="{% url 'view_category' item ***this part is tricky for me*** %}" class="stretched-link"></a> </div> </div> </div> {% endfor %} </div> </div> </div> {% endblock %} urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.home_page, name ='home_page'), path('feed/',views.feed, … -
"no schema has been selected to create" when running Django tests
After creating a Django test script for my Django project which uses Postegres, I also created the migrations file. Now, when I try to run ./manage.py test apis/tests/, I got the following error: Using existing test database for alias 'default'... Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.InvalidSchemaName: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): ... django.db.utils.ProgrammingError: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR... ^ During handling of the above exception, another exception occurred: Traceback (most recent call last): ... django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR... -
Separate by apps in drf-spectacular
Here it is the UI i can get from drf-spectacular redoc: enter image description here As you can see the only way to know the apps is from the names: v1_foo_foodcourtrests_des v1_ord_customer_basket_li Here foo and ord are app names. But I want to have a separator or something to separate these by the app names Here is what I got so far and still no luck: https://drf-spectacular.readthedocs.io/en/latest/settings.html#example-swaggerui-settings -
How to rename field names in Django
There are two models. CaseRequest is the list of requests and each containing the name and birth date of the applicant. Also, there is the Case table, and it's just a collection of all people. The idea is the following. Each CaseRequest must specify whether the same name and date of birth exist in the Case table. If it exists, CaseRequest displays yes, if it doesn't exist - no. In other words, we should know, is there the same name and date in another table or not. Models.py class CaseRequest(models.Model): name = models.CharField(max_length=255) datebirth = models.DateField() status = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('caserequest') class Case(models.Model): name = models.CharField(max_length=255) datebirth = models.DateField() def __str__(self): return self.name + ' | ' + str(self.datebirth) def get_absolute_url(self): return reverse('case_list') Views.py class CaseRequestView(ListView): model = CaseRequest template_name = 'caserequest.html' CaseRequest.html <div> {% for caserequest in object_list %} <div> <p>{{ caserequest.name }}, {{ caserequest.datebirth }}</p> <p>Status: {{ caserequest.status }}</p> <!-- It's required to show YES or NO here--> </div> </div> For instance, we have the Case table: name datebirth Jon Won 01.05.1998 Douglas Hensley 10.10.1943 Ben Wall 14.12.2000 Hog Pen 11.04.2012 And the following result in CaseRequest must be: name datebirth status … -
Django Forms: How to set choose select option class and set disabled or selected in forms.py
Is it possible in a simple way? I have in my forms Class class ExampleForm(forms.ModelForm): class Meta: CHOICES = (('Option 1', 'Option 1'), ('Option 2', 'Option 2'),) widgets = { 'classification': forms.Select(choices=CHOICES, attrs={'class':'form-select'}), } but i want to have <select> <option class="some-class" value="option 1" disabled>option 1</option> ... </select> How to add a class in options and also disabled? -
Complex constraint in Django with Q Objects
Two players can register for a tennis tournament which offers the doubles discipline (2 players compete against 2 other players). But there are some constraints: The same player may not register as player_01 for the same competition twice (same for player_02) A player may not register as player_01 if already registered as player_02 (with different partner) for the same competition (and vice versa) class Registration(models.Model): class Meta: abstract = True competition = models.ForeignKey(Competition, on_delete=models.CASCADE) class DoubleRegistration(Registration): class Meta: constraints = [ # 1. The same player may not register as player_01 for the same competition twice (same for player_02) models.UniqueConstraint( fields=['competition', 'player_01'], name='double_registration_unique_pl01'), models.UniqueConstraint( fields=['competition', 'player_02'], name='double_registration_unique_pl02'), # 2. A player may not register as player_01 if already registered as player_02 (with different partner) for the same competition (and vice versa) models.CheckConstraint( check=~Q(player_01=F('player_02') , competition=F('competition')), name='double_registration_pl01_already_registered'), models.CheckConstraint( check=~Q(player_02=F('player_01'), competition=F('competition')), name='double_registration_pl02_already_registered'), ] player_01 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name = 'doubles_player_01') player_02 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name = 'doubles_player_02') While the first constraint seems to work fine, the second constraint does not work. I am still able to first register Adam as player_01 and Kain as player_02 (which is fine) but then also register Adam as player_02 and Kain as player_01. Since the second … -
How to add a field to model with a decorator?
I'd like to add foreign keys to virtually every model in my app to allow different Sites. For this I think it would be nice to use decorators, because I will be able to only add those FKs under certain conditions (e.g. if Sites is installed). Unfortunately my attempt doesn't do anything: def add_site_fk_field(model_to_annotate: models.Model): """Add FK to Site to Model""" model_to_annotate.site = models.ForeignKey(Site, on_delete=models.CASCADE) return model_to_annotate @add_site_fk_field class Test(models.Model): ... Is it somehow possible to do this? I prefet not to use abstract classes. -
pip install mod_wsgi issue
install is failing and cant figure out why. ive spent a lot of time researching this issue and half of the people are saying the apache24 folder is in the wrong place, which ive double checked its correct. and the other half say its because windows sdk tools are not installed, which ive double checked they are. PS C:\Users\Mlong\Downloads\ZTP 4\ZTP> pip install mod_wsgi Collecting mod_wsgi Using cached mod_wsgi-4.9.4.tar.gz (497 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mod_wsgi Building wheel for mod_wsgi (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [31 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi creating build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server creating build\lib.win-amd64-3.10\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management creating build\lib.win-amd64-3.10\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.10\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\docs creating build\lib.win-amd64-3.10\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.10\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension creating build\temp.win-amd64-3.10 creating build\temp.win-amd64-3.10\Release creating build\temp.win-amd64-3.10\Release\src creating build\temp.win-amd64-3.10\Release\src\server C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\Apache24/include -IC:\Users\Mlong\scoop\apps\python\current\include -IC:\Users\Mlong\scoop\apps\python\current\Include -IC:\Program Files (x86)\Microsoft … -
Vulnerability issue Accept-Language headers are cached in order to avoid repetitive parsing on AWS ECR
I am getting this below high severity vulnerability issue on my AWS ECR image, I don't know what is causing it since I am using the latest version on Docker container of Django i.e 4.1.6. In Django 3.2 before 3.2.17, 4.0 before 4.0.9, and 4.1 before 4.1.6, the parsed values of Accept-Language headers are cached in order to avoid repetitive parsing. This leads to a potential denial-of-service vector via excessive memory usage if the raw value of Accept-Language headers is very large. -
Django: Overriding Postgres Database wrapper to set search path throws error
I want to establish a connection with a postgres database in django. As it doesn't provide support for postgres schemas I am trying to set the search_path immediately after establishing a connection. To acheive this I have subclassed the DatabaseWrapper class and overridden the _cursor method as below: from django.db.backends.postgresql.base import DatabaseWrapper class DatabaseWrapper(DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) def _cursor(self, name=None): cursor = super(DatabaseWrapper, self)._cursor(name) cursor.execute('SET search_path = schema_name') return cursor Now the above code works fine for the application code that we have written but when I try access the detail screen of any object in the admin panel of django, I get the below error trace: File "/Users/azharuddin.syed/Desktop/application/custom_db_engine/base.py", line 13, in _cursor cursor.execute('SET search_path = schema_name') File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: syntax error at or near "SET" LINE 1: ...6171701248_sync_1" NO SCROLL CURSOR WITH HOLD FOR SET search... If I understand … -
Crispy forms label inside of field
Using Bootstrap5, Django and Crispy Forms to create a calculator application. Application works as expected however I want to make changes to the appearance of the forms. I've already removed the required field asterisk by simply adding the following to the CSS file: .asteriskField { display: none; } But now I want to place the label inside the field which requires a different approach that I'm currently unable to understand despite extensive research. Having used Inspect in Chrome I can see that the label is of course a separate element but one housed within the field to achieve the given effect. Current Form Desired result Settings.py (excerpt) CRISPY_TEMPLATE_PACK = 'bootstrap5' Forms.py (excerpt) class InvestmentForm(forms.Form): starting_amount = forms.ChoiceField(choices=STARTING_AMOUNT) deposit_amount = forms.FloatField() trade_in_value = forms.FloatField() number_of_years = forms.FloatField() credit_score = forms.ChoiceField(choices=CREDIT_SCORE) state = forms.ChoiceField( label='State', choices=[(zipcode, zipcode) for zipcode in StateTax.objects.values_list('zipcode', flat=True).distinct()] ) Index.html (excerpt) <div class="row justify-content-center"> <h5 class="text-center"> Enter details below to see your estimate</h5> </div> <div class="col-md-8 mx-auto"> <form action="" method="POST"> {% csrf_token %} {{ form|crispy }} <br> <button class="btn btn-primary" type="submit">Calculate</button> </form> <br> </div> </div> -
Can I use DRF-SPECTACULAR for external API?
Currently using drf-spectacular with no issues on my site. However, I need to also document some APIs for separate app. Is it possible to use a json or yaml file to produce some swagger/redoc documentation? -
Django: In a ModelManager, how do I access a constant defined inside the related Model?
I have, for example, an Enum defined inside a Model. That model uses, and therefore imports, a ModeLManager. In that ModelManager, I'd like to access the Enum that I defined inside the Model; but I can't import the Model there or I'd get a circular dependency error. An example of the issue: Managers.py class CardManager(models.Manager): def spades(self): return self.filter(suit=2) Models.py from foo.managers import CardManager class Card(models.Model): class Suit(models.IntegerChoices): DIAMOND = 1 SPADE = 2 HEART = 3 CLUB = 4 suit = models.IntegerField(choices=Suit.choices) objects = CardManager() This code works perfectly well, but instead of having suit=2, I'd prefer to have something like suit=Card.Suit.SPADE. I can't find a way to make that reference work, though, as I can't import Card into Managers.py. Should I be defining the enum inside the ModelManager instead of the Model? All examples I've come across define them in the Model instead.