Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Favicon Not Displaying for Extracted Link Previews
I'm developing a Django application where users can create blog posts that include links. I want to display a preview of these links, including the website's favicon. However, despite implementing the logic to extract the favicon from the linked websites, it doesn't show up in the frontend. Here’s what I’ve implemented: Model Definition: I have a BlogPost model that includes a title, content, and a timestamp. from django.db import models class BlogPost(models.Model): title = models.CharField(max_length=200) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True, null=True) def get_link_previews(self): links = extract_links(self.content) previews = [] for url in links: previews.append(fetch_link_preview(url)) return previews Link Extraction Logic: I use regex to extract links from the blog post content. import re def extract_links(text): url_pattern = r'https?://[^\s]+' return re.findall(url_pattern, text) Preview Extraction Logic: I use requests and BeautifulSoup to extract the title, description, image, and favicon from the linked page. import requests from bs4 import BeautifulSoup def fetch_link_preview(url): try: response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') title = soup.title.string if soup.title else 'No Title' description = soup.find('meta', attrs={'name': 'description'}) description_content = description['content'] if description else 'No Description' image = soup.find('meta', attrs={'property': 'og:image'}) image_content = image['content'] if image else None # Find the favicon favicon_url = None for link in … -
Django system Not Logging User Out on Browser/Tab Close (Chrome/Safari)
Safari Incognito: Sessions expire as expected. Chrome Incognito: Sessions don't expire, regardless of settings. Regular Safari/Chrome: Sessions don't expire on tab or browser close. #middleware.py if manager: if client.logout_browser_close_manager: request.session.set_expiry(0) request.session.modified = True #settings.py SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SAVE_EVERY_REQUEST = True I can confirm the middleware.py is added to the middleware configuration in settings.py The session cookie shows session instead of a date with the following code, but does not log the user out. -
PyCharm autocomplete not working for context variables in Django templates
Normally, PyCharm autocomplete (code completion) works for context variables in Django templates. For example, if the context is {"question": question}, where question is an instance of the Question model, PyCharm will offer autocomplete suggestions when I start typing {{ question. }}, like this: However, in my current Django project, PyCharm autocomplete fails to work for context variables in Django templates. Even pressing Ctrl + Space will not bring up code completion suggestions: I think that I have everything configured in PyCharm for Django as usual for this project, although I could be mistaken. It's a larger project, so I suspect that something about the project structure itself might be causing the problem. Other convenience features are still working in Django templates, e.g., Emmet abbreviations, auto-closing of {{ and {%, etc. At first, I suspected the problem was that I have the models, views, etc., split out into multiple files. For example, instead of all models being contained in a single models.py file, the models are organized like this: models/ __init__.py model_a.py model_b.py model_c.py However, I don't think this is causing the autocomplete failure, because when I created a small Django project and organized it this way, autocomplete still worked for … -
Adds extra www when entering django admin panel
My website worked very well yesterday but today i have a problem. My website is https://www.622health.com.tr When i write https://www.622health.com.tr/admin and click enter, Its redirect to https://www.www.622health.com.tr/admin I made some redirect things for example 622health.com.tr to www.622health.com.tr , but this problem i removed all redirects but still i have an error. How can i fix this. I use ai for this but nothing. -
Django Postgres Json Filtering
there is a django model Model. It has a JSONField type field. There are approximately 1000 json files in postgresql in the table of this model. Json has a strict structure. 'food' -> foodid -> 'field' -> fieldname -> {....}. There can be arbitrary values instead of foodid and fieldname. How do I get unique possible pairs (foodid, fieldname) from postgres? Model.objects.annotate( foodid=Func( F('food'), function='jsonb_object_keys', output_field=models.CharField() ) ).annotate( field_name=Func( Value('food__') + F('foodid') + Value('__field'), function='jsonb_object_keys', output_field=models.CharField() ) ).values_list('food_id', 'field_names') The first annotate works. In the second annotate, I want to take the food_id field from the first annotate, but simply specifying F('foodidid__field'), the postgres will look for the foodid field in the table itself which does not exist. -
Django Error: DisallowedHost - Invalid HTTP_HOST header when using custom domain from Namecheap
I recently deployed a Django application on AWS EC2 and successfully accessed it via its public IP. I then purchased a domain from Namecheap (www.myproject.com) to use instead of the IP address. After configuring the domain, I encountered the following error when running Gunicorn with the command: gunicorn –bind 127.0.0.1:8001 wsgi:application Error traceback: DisallowedHost at / Invalid HTTP_HOST header: 'www.myproject.com,www.myproject.com'. The domain name provided is not valid according to RFC 1034/1035. Request Method: GET Request URL: http://www.myproject.com,www.myproject.com/ Django Version: 5.1.1 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: 'www.myproject.com,www.myproject.com'. The domain name provided is not valid according to RFC 1034/1035. Exception Location: /home/ubuntu/myproject/.venv/lib/python3.12/site-packages/django/http/request.py, line 151, in get_host Raised during: transcribe_audio.views.index Python Executable: /home/ubuntu/myproject/.venv/bin/python3 Python Version: 3.12.3 Python Path: ['/home/ubuntu/myproject/e', '/home/ubuntu/myproject/.venv/bin', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/home/ubuntu/myproject/.venv/lib/python3.12/site-packages', '/home/ubuntu/myproject'] Server time: Sun, 13 Oct 2024 13:37:50 +0000 From the error, it looks like the HTTP_HOST header is somehow being duplicated (www.myproject.com,www.myproject.com), which is causing the request to fail. I'm unsure why this duplication is happening and how to resolve it. NGINX Configuration: Here’s my NGINX config file: server { listen 80; server_name myproject.com www.myproject.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /path/to/your/static/files; } location / { proxy_pass http://127.0.0.1:8001; … -
Authentication Cookie Not Sent with Axios Request in Browser
I'm having trouble with cookie-based authentication in my Django + React app. I've set the cookie on the backend, but it's not being sent with subsequent requests from the frontend React (Using Vite) app running on Google Chrome. I'm trying to implement authentication using cookies in a Django backend using Simple JWT. After a successful login, I set an authentication cookie ("CAT") in Django. Here’s the code I use to set the cookie: final_response.set_cookie( "CAT", combined_token, httponly=True, secure=False, samesite="None", max_age=86400, path="/", ) return final_response Setting.py at the Django server: CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOWED_ORIGINS = ["http://localhost:5173/"] CORS_ALLOW_CREDENTIALS = True SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin" I can see the cookie stored in Chrome after logging in: However, when my React app makes subsequent requests, the browser doesn’t seem to include the cookie, and I get an authentication failure ("Cookie not found"). Here’s my Axios request setup in the React app: try { const auth_response = await axios.get( "http://my-django-server/api/auth/auth-checker", { headers: { "Content-Type": "application/json", }, withCredentials: true, timeout: 5000, } ); console.log(auth_response?.data); if (auth_response?.status === 200) { navigate("/profile"); } else { console.error("Unauthorized access. Please try again."); } } catch (error) { console.error("An error occurred. Please try again.", error); } Manual authentication works: Interestingly, when I … -
Products Not Filtering Correctly with AJAX in Django
I'm working on an e-commerce website using Django and jQuery to filter products based on selected criteria (price range, categories, and vendors). While the AJAX request seems to be sent correctly and I receive a response, all products are still displayed on the page, regardless of the selected filters. What I've Implemented: JavaScript (AJAX) Code: $(document).ready(function() { function filterProducts() { let filter_object = {}; // Get price range values let min_price = $("#price-min").val() || 0; let max_price = $("#price-max").val() || 9999999; filter_object.min_price = min_price; filter_object.max_price = max_price; // Get selected categories and vendors $(".filter-checkbox").each(function() { let filter_key = $(this).data("filter"); filter_object[filter_key] = Array.from( document.querySelectorAll('input[data-filter=' + filter_key + ']:checked') ).map(function(element) { return element.value; }); }); // Send AJAX request to filter products $.ajax({ url: '/filter-product', data: filter_object, dataType: 'json', beforeSend: function() { console.log("Filtering products..."); }, success: function(response) { console.log("Products filtered successfully."); $(".showcase").html(response.data); }, error: function(xhr, status, error) { console.error("Error filtering products:", error); } }); } // Event listener for checkbox and filter button $(".filter-checkbox, #filter-btn").on("click", filterProducts); }); HTML Structure: <div class="u-s-m-b-30"> <div class="shop-w"> <div class="shop-w__intro-wrap"> <h1 class="shop-w__h">PRICE</h1> <span class="fas fa-minus shop-w__toggle" data-target="#s-price" data-toggle="collapse"></span> </div> <div class="shop-w__wrap collapse show" id="s-price"> <form class="shop-w__form-p"> <div class="shop-w__form-p-wrap"> <div> <label for="price-min"></label> <input class="input-text input-text--primary-style" type="text" id="price-min" placeholder="Min"> … -
js not loading in html
This is the error that keeps coming up : 2/:47 Uncaught ReferenceError: moveSlide is not defined at HTMLAnchorElement.onclick (2/:47:64) onclick @ 2/:47 2/:48 Uncaught ReferenceError: moveSlide is not defined at HTMLAnchorElement.onclick (2/:48:63) But I just finished my javascript for the control carousel & the buttons but it seems like its not loading htmlwarningsjs I have tried and verified all my code but with no luck to find the issue I have also found something interesting when viewing my sources page in the inspectorhome page sources that shows my js scriptproject page that doesnt show my js in its sources let slideIndex = 1; showSlides(slideIndex) function moveSlide(n) { slideIndex += n showSlides(slideIndex) } function showSlides(n) { let slides = document.getElementsByClassName("carousel-item") if (n > slides.length) { slideIndex = 1 } if (n < 1) { slideIndex = slides.length; } for (let i = 0; i < slides.length; i++) { slides[i].style.display = "none" } slides[slideIndex - 1].style.display = "flex" } {% extends 'base.html' %} {% load static %} {% block title %} Project Page {% endblock %} {% block extrahead %} <link rel="stylesheet" href="{% static 'css/project.css' %}" /> {% endblock %} {% block content %} <div class="project-card"> <div class="project-info"> <h1>{{ project.title }}</h1> <p> … -
Sending array of texts to Django, via POST, cannot get as array, getting string
I'm sending this data to Django, these texts are from multiple CKEditors chk_vals = ["Some text","Other text"]; const data = new URLSearchParams(); data.append("csrfmiddlewaretoken", "{{csrf_token}}"); data.append("tmplData", JSON.stringify(chk_vals)); fetch(uri, { method: 'post', body: data, }) .then(response => response.json()) .then(data => { It's from Chrome's network: tmplData: ["Some text","Other text"] Now Django: data = request.POST templateArr = data.getlist('tmplData') templateList = list(templateArr) And the length of the templateList is 1, it is getting it as one string and I cannot split it with ',' because these texts can contain ',' too. I also tried templateArr = data.getlist('tmplData[]') and sending without JSON.stringify, but nothing works data = request.POST templateArr = data.getlist('tmplData[]') templateList = list(templateArr) and this variable templateArr is empty -
Add primary key for existing table
I have database table core_config and basic model core.Config model connected to it. Initial migration has definition of id AutoField as default, but there is no PRIMARY KEY in database table (I have no idea why), so I can't create relations to it from another tables. Is there any ways to generate migration like 'add_constraint_pk_if_not_exists'? I want to make it with "if_not_exists" because there is a probability of existing PRIMARY KEY in other database mirrors. -
Dockerized Django with Gunicorn not working
I'm attemtping to migrate to Gunicorn WSGI server for a Dockerized Django 5.0.4 Rest API running on 80:8080. Currently it is running with the default WSGI that ships with Django. However, I'm unable to set it up correctly. Definately missing something. Postman response still shows response as: Server : WSGIServer/0.2 CPython/3.10.14 Here is my configuration: Project structure mydjangoblogmain ---mydjangoblog -settings.py -wsgi.py -urls.py wsgi.py inside mydjangoblog """ WSGI config for mydjangoblogmain project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangoblog.settings") application = get_wsgi_application() My Docker File FROM python:3.10.14 RUN apt-get -y update && apt-get -y upgrade && apt-get install -y ffmpeg # Copy any files over COPY entrypoint.sh /entrypoint.sh # Change permissions RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] COPY requirements.txt /requirements.txt RUN pip install -r /requirements.txt VOLUME ["/opt/mydjangoblogmain"] EXPOSE 8080 CMD ["gunicorn","mydjangoblogmain.mydjangoblog.wsgi:application" ,"--bind", "0.0.0.0:8080", "--workers", "4" ] # CMD ["python", "manage.py", "runserver", "0.0.0.0:8080"] #Commented this out and used the CMD command before it. entrypoint.sh #!/bin/bash set -eo pipefail cd /opt/mydjangoblogmain # install pip env deps, run migrations, collect media, start the server pip install -r requirements.txt --quiet python manage.py migrate echo … -
Pros and Cons of Not Using ForeignKey in Django Through Table?
I'm working on a Django project and came across a design pattern that I'm unsure about. I have an intermediary table (through table) that connects Book and Tag. Instead of using ForeignKey fields for the relationships, the table uses plain IntegerField fields to store the IDs of the related models (book_id and tag_id). Here’s what the model looks like: class BookTagType(models.Model): book_id = models.IntegerField(null=True, blank=True) tag_id = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "book_tag_types" managed = False This model stores just the IDs of Book and Tag, but I’m wondering: Is there any reason or benefit not to use ForeignKey here instead of IntegerField? What are the potential drawbacks or advantages of using IntegerField for these relations compared to using ForeignKey? -
django unresolved tag "load" at DRF api.html
I have the following fully-functioning project/rest_framework/api.html: {% extends 'rest_framework/base.html' %} {% load static %} {% block style %} {{ block.super }} <link rel="stylesheet" href="{% static 'css/General.css' %}"> {% endblock %} the problem is, that load is underlined, commented "unresolved tag 'load'. As well no style changes apear on web page even after restarting the server and shift-f5 reload. -
How to efficiently structure conversion logic between model pairs in Django?
I'm working on a Django app where I need to handle conversions between pairs of models with different units of measurement. These models are like tasks which the user needs to complete, and converting units between two tasks attempts to map the effort of the first task to the second, measured in units. My current approach uses a mapping of model pairs (around 30 possible combinations) and applies one of several calculations to a value associated with the from_model based on the pair and the associated unit. I've been given a predefined list of mappings and calculations on the various units of measurement each task has. Context: For example, here are two tasks: Task A: Writing 1 page by hand using a pencil (this contains a value and unit of measurement). Task B: Typing pages using a computer (this does not contain a value, but does contain the unit of measurement) A conversion from Model A to Model B would need to take the value (e.g., 1 page) and return an equivalent in terms of effort (e.g., typing 3 pages might be considered equivalent to handwriting 1 page). Here's my current implementation: from django.test import TestCase from app.myapp.models import MyModel … -
Cors-erorr occurs when I send a post request, but corsheaders are configured
I want to make a post request for back end from front end, but I get an error in my browser. I tested it through postman - there are no problems with logic on the backend, and I have configured corsheaders correctly, I think. (frontend - Next.js) (backend - Django rest) settings.py CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000", ] CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_WHITELIST = [ "http://localhost:8000", ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] here's my this post request from the front, couldn't seem to find any errors in it either page.js 'use client' import styles from "./page.module.css"; import axios from "axios"; import { useState } from "react"; export default function Home() { const [data, setData] = useState([]); const [postData, setPostData] = useState({ password: "", message: "", }); const handleSubmit = async (event) => { event.preventDefault(); try{ const res = await axios.post("http://127.0.0.1:8000/message-post/", postData, { headers : { 'Content-Type': 'application/json' } }); const data = res.data; setData(data); } catch(error){ console.log(error); } } return ( <div> {data.map((dat, index) => ( <div key={index}> <a>{dat.message}</a> </div> ))} <form className={styles.formdata} method="POST" onSubmit={handleSubmit}> <div className={styles.input_fields}> <a className={styles.textupper}>Chatting anonymously</a> <input className={styles.password} type="text" placeholder="Enter password" value={postData.password} onChange={(e) => setPostData({...postData, password: e.target.value})}></input> <textarea className={styles.message} type="text" placeholder="Massage..." value={postData.message} … -
Issues with Django and MS SQL on Docker
I am trying to connect Django and MS SQL 2022 on Docker but I am getting the following error: 2024-10-12 16:20:30 /usr/local/lib/python3.11/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') Dockerfile (BE) FROM python:3.11.9-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update RUN apk add unixodbc-dev g++ bash gnupg curl #Download the desired package(s) RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/msodbcsql17_17.10.5.1-1_amd64.apk RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql-tools_17.10.1.1-1_amd64.apk #(Optional) Verify signature, if 'gpg' is missing install it using 'apk add gnupg': RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/msodbcsql17_17.10.5.1-1_amd64.sig RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql-tools_17.10.1.1-1_amd64.sig RUN curl https://packages.microsoft.com/keys/microsoft.asc | gpg --import - RUN gpg --verify msodbcsql17_17.10.5.1-1_amd64.sig msodbcsql17_17.10.5.1-1_amd64.apk RUN gpg --verify mssql-tools_17.10.1.1-1_amd64.sig mssql-tools_17.10.1.1-1_amd64.apk #Install the package(s) RUN apk add --allow-untrusted msodbcsql17_17.10.5.1-1_amd64.apk RUN apk add --allow-untrusted mssql-tools_17.10.1.1-1_amd64.apk RUN mkdir /code WORKDIR /code ADD . /code/ RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python","/code/manage.py","runserver","0.0.0.0:8000"] Dockerfile DB FROM mcr.microsoft.com/mssql/server:2022-latest ENV ACCEPT_EULA=Y ENV MSSQL_PID=Express ENV SA_PASSWORD=admin123! ENV MSSQL_TCP_PORT=1433 EXPOSE 1433 # Set the working directory inside the container WORKDIR /usr/src/app # Copy the SQL script to the container COPY init-db.sql . # Copy the … -
ListFlowable() causes drawing PDF file to stop using ReportLab in Django
I'm creating a Django project in which I can store recipes. Every recipe has the option to be exported in a PDF file. When creating the PDF file I'm appending every paragraph using Paragraph() to the PDF, except the ingredients part, which should be a list using ListFlowable() . If I append the ListFlowable() to the story list, the exported PDF file stops to be drawn at the moment it is called and no further paragraphs are added to the file (including the ListFlowable()). Yet, if I exclude the ListFlowable() from the story, every paragraph is being rendered in the PDF file. Does anybody know what's causing this to happen? generate_report.py: from io import BytesIO from reportlab.pdfgen import canvas from reportlab.platypus import Paragraph, Frame, ListFlowable, ListItem from reportlab.lib.styles import ParagraphStyle from reportlab.lib.units import mm from reportlab.lib.pagesizes import A4 from .models import RecipeIngredients from django.shortcuts import get_object_or_404 LEFT_MARGIN = 10*mm RIGHT_MARGIN = 10*mm TOP_MARGIN = 20*mm BOTTOM_MARGIN = 20*mm PAGE_WIDTH, PAGE_HEIGHT = A4 TEXT_WIDTH = PAGE_WIDTH - LEFT_MARGIN - RIGHT_MARGIN TEXT_HEIGHT = PAGE_HEIGHT - TOP_MARGIN - BOTTOM_MARGIN HEADING_1 = ParagraphStyle('Heading1', fontName="Helvetica", fontSize=16, alignment=0, spaceAfter=30) HEADING_2 = ParagraphStyle('Heading2', fontName="Helvetica", fontSize=12, alignment=0, spaceAfter=20) NORMAL = ParagraphStyle('Normal', fontName="Helvetica", fontSize=11, alignment=0, spaceAfter=10) def generate_pdf_recipe(recipe_slug): buffer … -
Django datatable: order by the last entry
I have a datatable with 11 columns. The first column is ID (pk) and the table is ordered by this primary key. order: [[1, 'desc']] I want to order all of the entries in my table by the last one added to the first one, as it is now, BUT I don't want some ID's to be skipped if I delete one record. I tried to order them by a column "Date", but this is not what I want. I tried to hide the column ID, but then I can't order by the last one added. Example: Before deletion: ID NAME 1 John 2 Smith 3 Mark 4 Johnny After deleting Smith (2) row: ID NAME 1 John 3 Mark 4 Johnny What I want: ID NAME 1 John 2 Mark 3 Johnny I am thinking about a new custom ID field but I want it to update everytime with the deletion of a middle record. Another way is to hide the column ID, but if I click to sort them by Name, I can't sort them back by ID only if I refresh the page. Do you have any solutions ? Thanks -
Issues with boilerplate HTML in the Django templates folder
"I've tried reinstalling all extensions, adjusting settings, and reinstalling VS Code, but the auto-suggestion of snippets in templates/index.html doesn't work. However, when I move index.html out of the templates folder to ./index.html, the snippets start working again. How can I fix auto-suggestions for snippets inside the templates folder?" What I tried: Reinstalled all VS Code extensions. Changed various settings related to snippets and auto-completion. Reinstalled VS Code entirely. Moved index.html out of the templates folder to ./index.html, which made the snippets work again. What I expected: I expected the auto-suggestion of snippets to work within templates/index.html, just as it does when the file is outside the templates folder. -
When the page is fully loaded, the visibility of the content is cut-off
In the first option - page loading mode - this is if you interrupt it at the loading stage and not completely. The page is not completely loaded. In this case - option - all the content is displayed in the browser - the content that has time to load is loaded accordingly - which had time to load before the interruption. In the second option - page loading - this is if you do not interrupt the loading and the loading is complete. All the content on the page is completely loaded. But at the moment - immediately upon complete loading - there is a cut-off - a reduction in the visibility of the content - you cannot fully view the - seemingly fully loaded page. The content is cut-off. It is possible that something is not working somewhere. Could this be - is it because of the side menu? I'm trying to create a shell for Django Python. And I have a strange thing - visibility - content availability is limited. Although everything seems to load when loading - but then when fully loaded for some reason - there is a limitation - there is no scrolling of … -
Django app on Vercel behaving differently when the DEBUG's value is changed
When I deploy a Django app on Vercel with DEBUG = False, it's showing "maximum unzipped size exceeded," but when I deploy the same Django app with DEBUG = True, it's working fine. Why so? This is the main problem. If more context is required, I will be more than happy to share. Thanks in advance -
ftplib doesn't send files in celery bot
I used a code from here to download files in Selenium Grid VMs, but, when I use FTP, it shows no error and it doesn't send the files. Code from ftp bot def is_connected(ftp): try: ftp.retrlines('LIST') except (socket.timeout, OSError, AttributeError): return False return True @shared_task() def send_binary(file_name : str, file_path): ftp = FTP( FTP_FAT_HOST, FTP_FAT_USER, FTP_FAT_PASSWORD, timeout=30 ) ftp.set_pasv(True) ftp.encoding='utf-8' if(not is_connected(ftp)): ftp.login() upload_to_ftp(file_path, ftp) def upload_to_ftp(local_file, ftp : FTP): try: with open(local_file, 'rb') as file: ftp.storbinary(f'STOR {os.path.basename(local_file)}', file) except Exception as e: print(f'Erro ao enviar {local_file}: {e}') Code I use to download pdf e txt files from my sources def __download_file(self, file_name: str, target_directory: str) -> None: if not os.path.exists(target_directory): os.makedirs(target_directory) contents = self.driver.execute(Command.DOWNLOAD_FILE, {"name": file_name})["value"]["contents"] zip_target_file = os.path.join(target_directory, f"{file_name}.zip") with open(zip_target_file, "wb") as file: file.write(base64.b64decode(contents)) with zipfile.ZipFile(zip_target_file, "r") as zip_ref: zip_ref.extractall(target_directory) os.remove(zip_target_file) Does anyone know another way to make it work ? I tried creating a bot in celery just to ftp, before this it was inside my main code. I tried change the ftp server, I tried change the ftp passiveness and timeout. Nothing changed. -
How to reset Django admin action page after returning a FileResponse
I have a Django Admin action that creates and downloads a file in response to a data export request from the user. The file download works fine, but the admin page is left in the same state as when the user first initiated the request, with the row that's being exported still ticked, and the export option still visible in the Admin action dropdown. How to I return a Django FileResponse, but also return a response that will reset the page? Can I return the FileResponse as part of a HttpResponseRedirect(request.get_full_path()) or something?? @admin.action(description="Export data for this edition") def export_edition_action(self, request, queryset): buffer = io.BytesIO() buffer.write(export_edition(queryset[0])) buffer.seek(0) response = FileResponse(buffer, as_attachment=True, filename=f'export.json') return response -
how celery flowers connect to redis throught ssh tunnel
I'm using ssh tunnel to connect to redis on remote host, but when I use ssh -L localport:target_remote_host:target_remote_port username@medium_remote_host to forwarding local request, I can connect to target remote redis by redis-cli. But when I start flower, It failed. Is there any wrong step? And I can start flower when the target host is medium host.