Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels unable to connect(find) websocket after dockerize the project
Before trying to containerize the application with docker, it worked well with: python manage.py runserver with the following settings.py setction for the redis layer: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("0.0.0.0", 6379)], }, }, } and by calling a docker container for the redis layer: docker run -p 6379:6379 -d redis:5 But after trying to containerize the entire application it was unable to find the websocket: Error message in firefox console : Error message docker-compose file: services: redis: container_name: redis image: redis:latest networks: - main ports: - "6379:6379" restart: always wsgiserver: container_name: wsgiserver build: . command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && python manage.py runserver 0.0.0.0:8000" volumes: - .:/source/ expose: - "8000" networks: - main environment: - EMAIL_HOST_USER=your_email@example.com - EMAIL_HOST_PASSWORD=your_email_password - CHANNEL_LAYERS_HOST=redis depends_on: - redis restart: always asgiserver: container_name: asgiserver build: . command: daphne -b 0.0.0.0 -p 9000 ChatApp.asgi:application volumes: - .:/source/ expose: - "9000" networks: - main depends_on: - redis - wsgiserver restart: always celery_worker: container_name: celery_worker command: "celery -A ChatApp worker -l INFO" depends_on: - redis - wsgiserver - asgiserver build: . environment: - C_FORCE_ROOT="true" - CELERY_BROKER_URL=redis://redis:6379/0 - CELERY_ENABLE_UTC=True - CELERY_RESULT_BACKEND=redis://redis:6379/0 - CELERY_TIMEZONE=Asia/Tehran networks: - main restart: always nginx: … -
Adding the search button and filter button to a single button in Django
Here I am trying to activate two functions with one button. How would it be to write the search button and filter system in a single function, as shown in the examples? I used the django filters framework for the filter. example image This is my views.py file def job_list(request): jobs = Job.objects.all().order_by('-date') locations = Location.objects.all() categories = Category.objects.all() jobtypes = JobType.objects.all() experiences = Experience.objects.all() qualifications = Qualification.objects.all() genders = Gender.objects.all() #filter start my_filter = JobFilter(request.GET, queryset=jobs) jobs = my_filter.qs #filter done context = { 'jobs': jobs, 'categories': categories, 'locations': locations, 'jobtypes': jobtypes, 'experiences': experiences, 'qualifications': qualifications, 'genders': genders, 'my_filter': my_filter, } return render(request, 'jobs.html', context) Here is my filters.py file import django_filters from . models import Job class JobFilter(django_filters.FilterSet): class Meta: model = Job fields = ['location', 'category', 'experience', 'qualification', 'jobtype', 'gender'] this is the search function I also defined a URL to the search function in url.py. def search(request): search_query = '' if request.GET.get('search'): search_query = request.GET.get('search') """aynı şeyleri göstermez... distinct""" jobs = Job.objects.distinct().filter( Q(name__icontains = search_query) | Q(description__icontains = search_query) | Q(category__name__icontains = search_query) ) categories = Category.objects.all() context = { 'jobs': jobs, 'categories': categories, 'search_query': search_query, } return render(request, 'jobs.html', context) I tried many functions but … -
DJANGO template variable not rendering in HTML
I'm working on a Django project, and I'm having trouble getting a variable to render in my HTML template. I have a view that passes a dictionary containing some data to my template, and I want to display a specific value in the HTML. Here's a simplified version of my view: def my_view(request): data = {'user_name': 'John Doe', 'age': 25} return render(request, 'my_template.html', {'data': data}) n my_template.html, I'm trying to display the user's name like this: html <!DOCTYPE html> <html> <head> <title>My Template</title> </head> <body> <h1>Welcome, {{ data.user_name }}!</h1> </body> </html> However, when I load the page, the user's name doesn't render. It just shows "Welcome, !" without the actual name. What am I doing wrong? Any help would be appreciated! yaml --- In this example, the user is facing an issue with rendering a Django template variable (`data.user_name`) in their HTML. They provide relevant code snippets from both the view and the template, explain the problem they are encountering (the variable not rendering), and express a need for assistance. This type of question allows the Stack Overflow community to offer insights and suggestions for resolving the problem. -
need to connect Django project with NGINX, certbot and ngrok
I have a Django project, made a file /etc/nginx/sites-enabled/griphr-backend which include : server { listen 80; server_name 31bb-156-220-68-78.ngrok-free.app; location / { proxy_pass http://localhost:8000; # Django app runs on port 8000 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } used the ngrok to get this domain 31bb-156-220-68-78.ngrok-free.app I run this command: sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful Now when run sudo certbot certonly --nginx -d 31bb-156-220-68-78.ngrok-free.app got this: Saving debug log to /var/log/letsencrypt/letsencrypt.log Which names would you like to activate HTTPS for? 1: 31bb-156-220-68-78.ngrok-free.app Select the appropriate numbers separated by commas and/or spaces, or leave input blank to select all options shown (Enter 'c' to cancel): 1 Requesting a certificate for 31bb-156-220-68-78.ngrok-free.app An unexpected error occurred: There were too many requests of a given type :: Error creating new order :: too many failed authorizations recently: see https://letsencrypt.org/docs/failed-validation-limit/ How make certbot work to generare ssl cert? -
Dynamic StatesGroup on aiogram 3.1.1
Good afternoon everyone. Curf work in a company developing telegram bots for businesses, the main stack is Django / Aiogram 3.1.1. At the moment I am faced with one difficult task and I would like to ask others about the possibility of its implementation. In short, the task is this: The database contains a table with questionnaires (field name, field question) and a table associated with the name of the question: the type of question validation (validation of number, name, mailbox, etc.), as well as a table with the user associated with the answer to the questionnaire. questionnaires and types DBdiagram My task is to create a kind of processor for filling out questions from these questionnaires. The difficulty is that, in fact, I could create a StateGroup and write it like this: class QuestionsStates(StatesGroup): email = State() phone_number = State() full_name = State() # . . .` Next, I would create handlers for each state, and after receiving and validating the data in the last state, the handlers would send the data to the database and that’s all. @router.message(QuestionsStates.last_state) async def send_data_to_backend(message: Message, state: FSMContext): user_answers = await state.get_data() # user_answer.get('') # send all data with user_id to backend … -
web_1 | Error: dictionary changed size during iteration
I have a Django Project. I have dockerized this project to run as container. Currently when I run this container using following command it shows following error at the end and exited docker-compose -f docker-compose-stag-prod.yaml up -d Docker Logs Output web_1 | Starting Gunicorn server... web_1 | 2023-12-05 18:20:18 [1] [INFO] Starting gunicorn 0.17.4 web_1 | 2023-12-05 18:20:18 [1] [INFO] Listening at: http://0.0.0.0:8000 (1) web_1 | 2023-12-05 18:20:18 [1] [INFO] Using worker: sync web_1 | /usr/local/lib/python3.10/os.py:1030: RuntimeWarning: line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used web_1 | return io.open(fd, mode, buffering, encoding, *args, **kwargs) web_1 | 2023-12-05 18:20:18 [6] [INFO] Booting worker with pid: 6 web_1 | 2023-12-05 18:20:18 [7] [INFO] Booting worker with pid: 7 web_1 | 2023-12-05 18:20:18 [8] [INFO] Booting worker with pid: 8 web_1 | 2023-12-05 18:20:18 [9] [INFO] Booting worker with pid: 9 web_1 | web_1 | Error: dictionary changed size during iteration I am not able to identify the line which is causing error. How can I identify the line number or code snippet which is causing issue. Also my application is running inside container using gunicorn exec gunicorn --bind 0.0.0.0:${PORT:-8000} --timeout 300 -w 4 -t 4 … -
Postgresql causing memory problems in django
I recently started getting this error Python(43052,0x7000021e4000) malloc: *** error for object 0x1: pointer being freed was not allocated Python(43052,0x7000021e4000) malloc: *** set a breakpoint in malloc_error_break to debug on launching my local Django server. I know Python has nothing to do with malloc which is a C library, and this kind of leaves me powerless, as I don't really know C... Shouldn't python do all this automatically? I figured that when I disconnect my PostgreSQL database (i.e. just comment out the DATABASES= ... ) in my settings.py the error goes away. It of course doesn't run my project as it relies on the database, but at least the error happens within the app. If I bring back the DATABASES, Django doesn't even start the app, as the error happens right on server startup and is only logged in the console. What's interesting is that the very same version of the program, but deployed to my production server on Azure works perfectly. -
Django: launch a django-independent python script
I have a Django + script launch problem. For context: I'm creating a website in Django that uses a database that isn't huge at the moment, but will grow over time. I've created my own administration according to my needs. A requirement is a retroactive action on the entire database. In order not to affect the website, the operation is carried out via another python script (which is not in views.py). The script lasts a minute and if I launch it from views.py, the site "freezes" on my side and I can no longer browse. That's why I've decided to create a separate script. My problem is that I need Django to launch this script without impacting the front-end, i.e. if I click on the script launch button on the front-end, I can continue browsing. I tried using subprocess : subprocess.run(['python3', '/home/ec2-user/scripts/database_cleaning.py']) Fun fact: the site seems frozen (I've got a spinning wheel on the tab name), but I can navigate and the script seems to work. On the other hand, it sometimes causes bugs when I'm browsing: a psycopg2 transaction doesn't close and the site is "KO'd" until I kill the process directly on PostgreSQL. So it seems that … -
Styling a NavBar in Django Python API
I`ve been trying to style the NavBar(image attached) on my API Project with no success. How could i position these 3 blocks equally on any screen (in the image is 80%)? Should i place them inside card?! Any suggestion?! I had to add a bunch of ** ** to show how it would like the proper way. <header> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="collapse navbar-collapse" id="navbar"> <div> <form action="{% url 'add_stock' %}" class="form-inline my-2 my-lg-0" method="POST"> {% csrf_token %} <button class="btn btn-outline-primary my-2 my-sm-0" type="submit"> <a><i class="fa fa-plus-circle" aria-hidden="true"></i>&nbsp; Add to Portfolio </a> </button> &nbsp; <input class="form-control mr-sm-2" type="search" placeholder="Enter a ticker" aria-label="Search" name="ticker"> </form> </div> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div> <button class="btn btn-flip" id="getStock" > <h5><strong> STOCK SCRENNER </strong></h5> </button> </div> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; … -
Send data by href (html) and get it with request function (django)
I have a html page where I looping on model fields. Html is: {% for problem in problems_list %} <p> {{ problem.id }} - {{ problem.incident_date }} - {{ problem.incident_specs }} - {{ problem.incident_location }} - {{ problem.incident_reason }} {% for action in actions_list %} {% if action.action_incident_id_id == problem.id %} <form method="post"> <input hidden name='problem_id' value="{{ problem.id }} "> <a class="btn btn-primary" type="submit" href="{% url 'ex_action' %}"> Button </a> <!-- action="{% url 'ex_action' %}"--> </form> {% endif %} {% endfor %} </p> {% endfor %} And here is a ex_action function: def ex_action(request): return render(request, 'problems/ex_action.html', {'actions_list': actions_list}) It works well, but I need to pass a problem.id from for loop into ex_action, and I don't know how to do it. I tried some constructions like href="{% url 'ex_action'?=problem_id=problem.id %}" and get it by something like request.GET.get('problem_id') or request.GET['problem_id'], but got TemplateSyntaxError on html, none as result on django code or MultiValueDictKeyError. Read a lot of docs\issues, and find what people use ajax\js to solve it, but I don't know how. Please help. -
Getting 403 MissingAuthenticationTokenException with OPTIONS Requests in AWS API Gateway
I am building a web app using React, Django and AWS. I have a Rest API on API Gateway that is giving a 403 "MissingAuthenticationTokenException" that seems to be specifically on OPTIONS requests. I am quite confused as I haven't set any authentication on the API and even have included an API key to try and fix it. This is what the error looks like on the console: Console Error: Console Error And when I looked at the network I see that it is caused by a 403 error: Preflight Error: Preflight Error Cors Error: Cors Error Network Error: Network Error On my react front-end I call the API on a button press: const formData = new FormData(); formData.append("image", selectedFile); try { await axios({ method: "put", url: "https://my-api.execute-api.eu-west-2.amazonaws.com/dev/photos/", data: formData, headers: { "Content-Type": "multipart/form-data", "x-api-key": "abc123" } }); } catch (error) { console.error(error); } And on my Django views.py it looks like this: def upload_image(request, bucket, filename): if request.method == 'OPTIONS': # Respond to preflight request with a 200 OK response = Response({'message': 'Preflight request successful'}) response['Access-Control-Allow-Origin'] = '*' # Update with your specific origin(s) response['Access-Control-Allow-Methods'] = 'PUT, OPTIONS' response['Access-Control-Allow-Headers'] = 'Content-Type, X-Amz-Date, Authorization, X-Api-Key, X-Amz-Security-Token' response.statusCode = 200 # … -
I'm getting a rejected error when trying to deploy a Django app to Heroku
I'm encountering issues while trying to build my Python app on the Heroku-22 stack. I'm using scikit-learn==0.23 as a dependency, and the build process is failing with various Cython compilation errors.Here's the error log I'm receiving: Building on the Heroku-22 stack Using buildpack: heroku/python Python app detected No Python version was specified. Using the buildpack default: python-3.11.6 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes "getting dependencies" Installing python-3.11.6 Installing pip 23.3.1, setuptools 68.2.2 and wheel 0.42.0 Installing SQLite3 Installing requirements with pip Collecting absl-py==1.4.0 (from -r requirements.txt (line 1)) Downloading absl_py-1.4.0-py3-none-any.whl (126 kB) Collecting asgiref==3.7.2 (from -r requirements.txt (line 2)) Downloading asgiref-3.7.2-py3-none-any.whl.metadata (9.2 kB) Collecting asttokens==2.0.8 (from -r requirements.txt (line 3)) Downloading asttokens-2.0.8-py2.py3-none-any.whl (23 kB) Collecting astunparse==1.6.3 (from -r requirements.txt (line 4)) Downloading astunparse-1.6.3-py2.py3-none-any.whl (12 kB) Collecting Babel==2.11.0 (from -r requirements.txt (line 5)) Downloading Babel-2.11.0-py3-none-any.whl (9.5 MB) Collecting backcall==0.2.0 (from -r requirements.txt (line 6)) Downloading backcall-0.2.0-py2.py3-none-any.whl (11 kB) Collecting bcrypt==4.0.1 (from -r requirements.txt (line 7)) Downloading bcrypt-4.0.1-cp36-abi3-manylinux_2_28_x86_64.whl (593 kB) Collecting beautifulsoup4==4.6.0 (from -r requirements.txt (line 8)) Downloading beautifulsoup4-4.6.0-py3-none-any.whl (86 kB) Collecting bs4==0.0.1 (from -r requirements.txt (line 9)) Downloading bs4-0.0.1.tar.gz (1.1 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Collecting cachetools==5.3.0 (from -r requirements.txt (line 10)) Downloading … -
Dockerize Django and Tailwind CSS
I'm totally new to Docker. I am developing by scanning templates folders with Tailwind CSS. I use 2 separate commands for development; python manage.py runserver and npm run dev So how do I do this when installing a docker container? Or should I do something different? -
I have a web app hosted on PythonAnywhere and it seems to be working fine on Chrome in Windows but on my phone not all the features are displayed
I have hosted a Django application on PythonAnywhere at anavenger9.pythonanywhere.com. The application works the way it should on my laptop but when I go to the site on my phone the navigation bars I created using Bootstrap5 are missing. What should I do? I tried disabling Forced https but it did not work. -
How to translate a variable template ( random value ) in django
I want to build a website using Django. My website supports two languages, English and Vietnamese. In models.py : from django.db import models class Order_product(models.Model): name = models.CharField(max_length = 255) note = models.TextField() status = models.CharField(max_length = 255, choices = [('Pending', 'Pending'), ('Need-Delivery', 'Need-Delivery'), ('Delivery', 'Delivery'), ('Success', 'Success'), ('Return-Order', 'Return-Order'), ('Cancel', 'Cancel')]) In views.py i have code like that from django.shortcuts import render from .models import * def test(request): get_order = Order_product.objects.all() return render(request, 'test/test.html', {'get_order ':get_order}) In template test.html {% for each_order in get_order %} <p> {% blocktranslate %} {{ each_order.status }} {% endblocktranslate %} </p> {% endfor %} after that, i run : python manage.py complimessages. In django.po file i have : msgid "" "\n" " %(each_order.status)s" " " msgstr "" I want to translate the template variable each_order.status based on its value. If the variable each_order.status has the value 'Success,' it should be translated to 'Thành công' in Vietnamese, ... How can I use Django for translation? I've done a lot of research but haven't found a suitable solution. Thank you very much. -
How do I rotate a Paragraph in reportlab in SimpleDoc Template
I have this reportlab pdf generator app I am building and I am using SimpleDocTemplate as my page template. I cannot seem to be able to rotate a Paragraph by 90 degrees as intented. Does anyone have a solution to this? #---- file_number1 = f"<font name='Helvetica' size='11'><b>{parcel.FileNumber}</b></font>" file_number1_style = styles['BodyText_FileNumber'] file_number1_style.leftIndent = -320 file_number1_data = Paragraph(file_number1, file_number1_style) elements.append(file_number1_data) elements.append(Spacer(1, -5)) #---- There is no rotate attribute on Paragraph. Is there another way? -
tying to install mysqlclient in Windows 11 getting an error
I want to install pip install mysqlclient but also pip install mysql on a Windows 11 Machine, I am getting the below error, I have already search to fix this error, but not get successful, how can I install mysqlclient? because I want to migrate my django project data to the mysql database? "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD "-Dversion_info=(2, 2, 0, 'final', 0)" -D__version__=2.2.0 -IC:/mariadb-connector\include\mariadb -IC:/mariadb-connector\include "-IC:\Users\Jamshid\OneDrive\Documents\My Programming Practices\Python\Basic CRM Tool\dcrm\virt\include" -IC:\Python312\include -IC:\Python312\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\cppwinrt" /Tcsrc/MySQLdb/_mysql.c /Fobuild\temp.win-amd64-cpython-312\Release\src/MySQLdb/_mysql.obj _mysql.c src/MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mysqlclient Failed to build mysqlclient ERROR: Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects -
Can't varify access token in middleware nextjs
I am trying to verify my token in nextjs middleware using jose library.But if any case the code gose into the catch block it the enter into a infinite loop and dosen't redirect to the login page.Actually,i have never authenticate token before so i am kind of confused what should i do. This problem specially happened when someone change the access token in the browser.This is my code that i have done so far. import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { jwtVerify } from 'jose'; export default async function middleware(request: NextRequest) { const access = request.cookies.get("access")?.value; const url = request.url; const urlStartWithUrl = `${process.env.NEXT_PUBLIC_HOST_FRONTEND}/open-bo-account`; const redirectUrl = `${process.env.NEXT_PUBLIC_HOST_FRONTEND}/login/`; if (!access && request.nextUrl.pathname.startsWith('/open-bo-account')) { request.cookies.clear() return NextResponse.redirect(new URL('/login', request.url)); } else if (access) { try { const secret = new TextEncoder().encode( "secret key" ); const decodedToken = await jwtVerify(access, secret); if (decodedToken) { return NextResponse.next(); } request.cookies.clear(); return NextResponse.redirect(new URL('/login', request.url)); } catch (error) { const cookiesBeforeClear = request.cookies.getAll(); console.log("Cookies before clear:", cookiesBeforeClear); request.cookies.clear(); const cookiesAfterClear = request.cookies.getAll(); console.log("Cookies after clear:", cookiesAfterClear); return NextResponse.redirect(new URL('/login', request.url)); } } } -
Why is my global dictionary value is changed in different views in Django?
In my Django app I have a global dictionary that stores some instances of a Class. Valu of this dictionary is being changed by one of my Django views. Then I use that global dictionary inside my other views. The problem is, in production, when I access this global dictionary in other views, value of it is changed (global dictionary changes to its initial value). I deployed Django app on Ubuntu server using Gunicorn and Nginx. Here is the scenario: my_global_dict = {} # This is the global dictionary with initial value of empty dict def view1(request): my_global_dict["key0"] = myClass() # Adding my class instance to the global dict ... def view2(request): print(my_global_dict) # Prints: {}. The global dict is empty in this view and others ... I emphasize that there is no problem in the process in the development environment. Also it works with Apache and IIS with ease. The problem I'm facing is after deploying on Gunicorn and Nginx. Thanks in advance! -
django-hitcount not recording ip adresses in hit
So, i'm using django-hitcount to keep track of user hits in my application. the application uses uuid as primary key for id of the books. so, i did a little modification to the django-hitcount code from here. the exact new version isnt compatible so i used it upto a specific commit. the forked repo is here. I only changed the object_pk on the hitcountbase model to uuid and removed the previous id which was used as a primary key. You can check the commit in here Running it on my project it is not recording the ip addresses of the hits and putting in the default 10.0.0.1 ip address on every data it tracks. Did I miss to change something while making it work with uuid? -
Django Convert image format to .webp (ResizedImageField)
I'm trying to use ResizedImageField instead of ImageField in Django to convert image files to .webp format. Most of the images work fine, but I'm having an issue with raw images taken by my iPhone. When I upload these raw images, they are rotated 90 degrees for some reason. However, if I edit these raw images (like cropping them), they are not rotated. I'm using django-resized version 1.0.2. This is my models.py class ArticleImage(models.Model): # upload_file = models.ImageField(upload_to='article/image/%Y/%m/%d/', null=True, blank=False) upload_file = ResizedImageField(size=None, upload_to='article/image/%Y/%m/%d/', quality=95, force_format='WEBP', null=True, blank=False) article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='image', null=True) def delete(self, *args, **kargs): # 데이터 삭제 시, 실제 파일도 삭제 if self.upload_file: os.remove(os.path.join(settings.MEDIA_ROOT, self.upload_file.path)) super(ArticleImage, self).delete(*args, **kargs) def filename(self): return os.path.basename(self.upload_file.name) This is my setting.py DJANGORESIZED_DEFAULT_KEEP_META = False DJANGORESIZED_DEFAULT_QUALITY = 95 DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'WEBP' DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'WEBP': ".webp"} DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = False I have tried adding DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = False, but still does not work. -
How do I run code once immediately after an object is created?
I'm working on an internal tool built using Django. Part of what we're doing with this tool is digitizing content from old PDFs. The PDFs have been through some kind of OCR process, but it has left them with frequent doubled or tripled spaces and hard returns at the end of every line. We're using this text to create database objects in Django's built-in admin. Imagine I have a data model like this: import re from django.db import models from django.db.models import CharField, TextField class Widget(models.Model): name = CharField() description = TextField() def fix_description(self): self.description = re.sub(r"\s+", " ", self.description) self.description = re.sub(r"\\n", "\n", self.description) self.description = re.sub(r" *\n *", "\n", self.description) Most of the time, the text in description will be a single paragraph. Occasionally it should contain actual line breaks, which I'd like to denote by typing \n into the description field in Django admin when creating the object. The fix_description method cleans up unintended whitespace exactly as we'd like, and keeps line breaks entered manually. What I'd like is to have fix_description run exactly once when the object is created through the Admin form, and then never again. I don't want to worry about having this code … -
How can I use a variable in the field of m2m?
First I am extracting the model name of the M2M field from the value I get through the loop. Then I am trying to add data to m2m table, but this AttributeError: 'ProductAttributes' object has no attribute 'm2m_model' is coming. attribute = ProductAttributes.objects.get(pk=pk) for key in common_keys: if initial[key] != new_data[key]: # Getting m2m model in lower case m2m_model = apps.get_model(app_label=app, model_name=key)._meta.model_name attribute.m2m_model.add(new_data[key]) Here's the problem attribute.m2m_model.add(new_data[key]) If I directly name the field then it works fine like below: attribute.color.add(new_data[key]) attribute.ram.add(new_data[key]) I want to make it dynamic. Here is my model: class ProductAttributes(models.Model): color = models.ManyToManyField('Color') band_color = models.ManyToManyField('BandColor') ram = models.ManyToManyField('RAM') vram = models.ManyToManyField('VRAM') Thanks in advance, any help would be much appreciated. -
Fuzz-testing Django application with atheris
I'm running my Django-project: cd PycharmProjects/Autopark source venv/bin/activate python3 manage.py runserver This is insides of project's wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'autopark.settings') application = get_wsgi_application() After that I open another tab of my terminal (I'm using Linux Mint) and start my fuzz-test script via the same venv: source venv/bin/activate python3 fuzz_test1.py That's first few strings from that file: import os import django django.setup() from django.test import Client client = Client() And I have an error at django.setup(): Traceback (most recent call last): File "/home/paberu/PycharmProjects/Autopark/fuzz_test1.py", line 4, in <module> django.setup() File "/home/paberu/PycharmProjects/Autopark/venv/lib/python3.10/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/paberu/PycharmProjects/Autopark/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/home/paberu/PycharmProjects/Autopark/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 72, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't have any idea of what am I doing wrong. Can you help me get rid of that error? -
mysql: how to resolve duplicate key errot
My django project has a migration that creates a foreign key on a table. When the migrate command is executed, I receive a stacktrace with error : MySQLdb._exceptions.OperationalError: (1061, "Duplicate key name "..." I located the key in table_constraints and in table_constraints_extensions. It doesn't appear to be in any other constraint table. There is one instance of the same key in each table. The foreign key was created, and actually works, but the migration fails to complete due to duplicate keys. I'm just not sure exactly where the duplication is because the FK constraint appears once in each of the tables mentioned above. My project can function without doing anything further, but the migration process will be broken until I fix this in the db. How and where do I fix this problem? delete from table_constratins ... alter table projects_project drop constraint ...