Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use a JavaScript variable as a variable in Django templating language?
I have the following code in a template ("home.html") in my Django project function deleteData(toBeDeleted) { $.ajax({ type: "GET", url: "{% url 'delete_data' **[Replace me]** 'all' %}", success: function (data) { alert(data) } }) } I need to reach the url 'delete_data' with 2 arguments where the 2nd argument is 'all' and the 1st argument is a javascript variable called "toBeDeleted" (Passed in as a function argument) A work around i have thought about is... url: `/delete_data/$(toBeDeleted)/all`, But in that case i will have to change that as well when changing the url for deleting data other than just changing the urls.py file Is there a way to make this work or do i have to give up on using {% url ... %}? -
Django TrigramSimilarity error for searches
I'm trying to use TrigramSimilarity for my django project to query it for search results but it's giving me an error like this: function similarity(text, unknown) does not exist LINE 1: ... COUNT(*) AS "__count" FROM "blog_blogpost" WHERE SIMILARITY... Here is my code query = request.GET['query'] if len(query) > 70: posts = BlogPost.objects.none() else: search = BlogPost.objects.annotate(similarity=TrigramSimilarity("body", query),).filter(similarity__gt=0.3).order_by("-similarity") paginate_search = Paginator(search, 12) page_search = request.GET.get("page") As it says that the function similarity is not defined. Is there a way to import similarity? As per my knowledge there are no such imports in django. -
Passing Data for Each User from one Django app to another?
In my Django application, users can log in using their username and password. Once logged in, the user makes a selection through a dropdown menu in an app.py created with dash-plotly. I want to retain this selection made by the user in memory and use it as an input for another app.py. I attempted to use an API, but it didn't provide a user-specific solution. Do you have any suggestions regarding this matter? Should I try using Models? I tried API and DjangoDashConsumer and I could not reach the solution. -
Why am I getting a NoneType for Allowed Host in Django-Environ when I set allowed host?
The settings code is import os import environ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) env = environ.Env(DEBUG=(bool, False)) environ.Env.read_env(os.path.join(BASE_DIR, '.env')) the allowed host is written as ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS").split(',') the .env file has ALLOWED_HOSTS as ALLOWED_HOSTS=localhost 127.0.0.1 [::1] why am I getting the fail code AttributeError: 'NoneType' object has no attribute 'split' when I run the command docker-compose up --build -d --remove-orphans -
Django - Fake Class representation in Django Admin
Sorry in advance for the complexity of my explanation. Assuming two classes ClassA and ClassB: class ClassA: # ... complexJoinKey=models.CharField(max_length=255) class ClassB: # ... complexJoinKey=models.CharField(max_length=255) The complexJointKey is a string handling complex values. It's in the shape: foo;a;*;b. There is an inclusion function (e.g. the previous example includes foo;a;bar;b), it's used to make some matches between ClassA and ClassB ; There should be a tree view ("foo", then "a", then "bar", then "b") to allow filtering which ClassA and ClassB share common filtering ; and every ClassA and ClassB has almost different complexJointKey ; I started by creating a simple foreign Key with a JointKey(Models.model) class, but this is bloaty in database: I get one object for each ClassX generated and I can't perform a nice filtering by tree.. Do you have a good implementation of this scheme? I thought about having a non-stored, virtual class with a ModelAdmin implementing the proper tree filtering, but following current Stakoverflow examples are to complex for my entry-level of Django. Thank you, -
Why i cant get the second components the other page with include
This is 'urunler.html' in my page {% extends "base.html" %} {% block site-title %} Ürünlerimiz {% endblock site-title %} {% block site-icerik %} {% include "./Components/_arts.html" %} {% endblock site-icerik %} include doesnt working. but in the index.html working {% extends "base.html" %} {% block site-title %} Anasayfa {% endblock site-title %} {% block site-icerik %} <!-- Swipper Slider --> <div class="container"> <div class="row justify-content-center"> <div class="col-md-6 mt-5"> {% include "./Components/_swipper.html" %} </div> </div> </div> <!-- Swipper Slider End --> <!-- Hakkımızda Section --> <section id="Hakkımızda"> <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-5"> <hr> </div> <div class="col-md-2"> <p class="text-center mx-0 my-0 m-0">Yeni Çalışmalar</p> </div> <div class="col-md-5"> <hr> </div> </div> <!-- Yeni Çalışmalar Col ve Row Start --> {% include "./Components/_arts.html" %} <!-- Yeni Çalışmalar Col ve Row End --> </div> </section> <!-- Hakkımızda Section End --> {% endblock site-icerik %} why this components not working different pages ? also maybe want the see view.py from django.db.models import Q from django.shortcuts import render, redirect from .models import Tasarim, Hakkimizda # djangonun user modelini dahil et from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout # Create your views here. def index(request): context = {} urunler = Tasarim.objects.all() context['urunler'] = … -
Excluding DJStripe Logs in Django
Im trying to exclude the djstripe logs from my django and prevent them being printed to the console. I have this config in my settings.py but when i perform Stripe operations I still see them on the console. LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "file": { "level": "DEBUG", "class": "logging.FileHandler", "filename": BASE_DIR / "web_debug.log", }, "console": { "level": "INFO", "class": "logging.StreamHandler", }, "djstripe_file": { # File handler specifically for djstripe "level": "DEBUG", "class": "logging.FileHandler", "filename": BASE_DIR / "djstripe.log", }, }, "loggers": { "djstripe": { # Logger specifically for djstripe "handlers": ["djstripe_file"], # Using the djstripe_file handler "level": "WARNING", "propagate": False, }, }, "root": { # Correctly defining the root logger outside the "loggers" dictionary "handlers": ["console"], "level": "INFO", }, } Any ideas? -
`dir()` doesn't show the cache object attributes in Django
I can use these cache methods set(), get(), touch(), incr(), decr(), incr_version(), decr_version(), delete(), delete_many(), clear() and close() as shown below: from django.core.cache import cache cache.set("first_name", "John") cache.set("last_name", "Smith") cache.set_many({"age": 36, "gender": "Male"}) cache.get("first_name") cache.get_or_set("last_name", "Doesn't exist") cache.get_many(["age", "gender"]) cache.touch("first_name", 60) cache.incr("age") cache.decr("age") cache.incr_version("first_name") cache.decr_version("last_name") cache.delete("first_name") cache.delete_many(["last_name", "age"]) cache.clear() cache.close() But, dir() doesn't show these cache methods as shown below: from django.core.cache import cache print(dir(cache)) # Here [ '__class__', '__contains__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_alias', '_connections' ] So, how can I show these cache methods? -
AppRegistryNotReady("Apps aren't loaded yet.")
I call a method clienting from another file in the admin.py @admin.register(Currency) class CurrencyAdmin(admin.ModelAdmin): list_display = ('name', 'symbol', 'position') change_list_template = "currency_changelist.html" def get_urls(self): urls = super().get_urls() my_urls = [path('getCurrency/', self.getCurrency), ] return my_urls + urls def getCurrency(self, request): clientWork = Process(target=clienting) clientWork.start() return HttpResponseRedirect("../") There are only 2 lines in this file, but if I add from screener.db_request import get_keys there, I get this error. What could be the problem? #from screener.db_request import get_keys def clienting(): print("Good") Error : Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\fr3st\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 120, in spawn_main exitcode = _main(fd, parent_sentinel) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fr3st\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 130, in _main self = reduction.pickle.load(from_parent) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fr3st\Desktop\Python\screener\clientWork.py", line 1, in <module> from screener.db_request import get_keys File "C:\Users\fr3st\Desktop\Python\screener\db_request.py", line 1, in <module> from .models import BinanceKey File "C:\Users\fr3st\Desktop\Python\screener\models.py", line 4, in <module> class BinanceKey(models.Model): File "C:\Users\fr3st\Desktop\Python\.venv\Lib\site-packages\django\db\models\base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fr3st\Desktop\Python\.venv\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "C:\Users\fr3st\Desktop\Python\.venv\Lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Matching query does not existt
I have this error 'Product matching query does not exist.' , i didn't have this error until I deleted the categories and items from my db.sqlite3 , after i created new categories and items for each category the error occurred. enter image description here enter image description here Thank you for any help. -
Django master template doesn't display title block
I'm a bit of a noob regarding django framework. I started learning it today and I already have an issue with what I've done and I couldn't figure out why. I wanted to setup a master template, called master.html and use 2 other pages: all_members.html and details.html Here is the exact code: master.html <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %} {% endblock %} </body> </html> all_members.html {% extends "master.html" %} {% block title %} My Tennis Club - List of all members {% endblock %} {% block content %} <h1>Members</h1> <ul> {% for x in mymembers %} <li><a href="details/{{ x.id }}">{{ x.firstname }} {{ x.lastname }}</a></li> {% endfor %} </ul> {% endblock %} details.html {% extends "master.html" %} {% block title %} Details about {{ mymember.firstname }} {{ mymember.lastname }} {% endblock %} {% block content %} <h1>{{ mymember.firstname }} {{ mymember.lastname }}</h1> <p>Phone {{ mymember.phone }}</p> <p>Member since: {{ mymember.joined_date }}</p> <p>Back to <a href="/dev">Members</a></p> {% endblock %} Here is what the page looks like: To be sure, the title "My Tennis Club" should be displayed, right ? I can't figure out why it could not... Thank you for your … -
Optimising Django .count() function
Is there a way to optimise the .count() function on a queryset in Django? I have a large table, which I have indexed, however the count function is still incredibly slow. I am using the Django Rest Framework Datatables package, which uses the count function, so I have no way of avoiding using the function - I was hoping there would be a way to utilise the index for the count or something along those lines? Thanks for any help anyone can offer! -
download file from url in django
I want to download a file from a URL. Actually, I want to get the file from a URL and return it when the user requests to get that file for download. I am using this codes: def download(request): file = 'example.com/video.mp4'' name = 'file name' response = HttpResponse(file) response['Content-Disposition'] = f'attachment; filename={name}' return response but it cant return file for download. These codes return a file, but the file is not in the URL. how can I fix it? -
Handle file downloads in Flutter and InAppWebView?
I have a Django server with an endpoint to generate a PDF with some information entered by the user which returns a FileResponse (everything with a buffer, no file is created in the server, it is generated on demand), so the PDF is returned as attachment in the response. The endpoint is called in a HTML form submit button (in a Django template) and it works perfectly in all browsers. On the other hand, I did an app with Flutter (Android and iOS) using the InAppWebView library which opens my webpage. The problem comes when I try to download the PDF using the app. I have not found any way of handling the download file when it is returned as an attachment, for all methods I found I need the URL (which I can not call as I need the form information and the file is generated on demand). Summarizing: I have a Django server and a template with a basic form. On the form submit, it calls a python function that generates and returns a FileResponse with a PDF as an attachment and doesn't save any file in the server. On the other hand I have a Flutter WebView … -
Django authentication problem with mysql database
I am working on a Django project which uses Mysql database to manage user authentication and I also developed a custom user model with the AbstractBaseUser class I can migrate the table in the database and insert a user to the database by using the createsuperuser function and everything is ok but when I try to authenticate the mentioned user, the authenticate function returns None. The strange thing is that when I use default Myadmin db.sqlite3 database service of Django, authenticate function works correctly and returns the user username = 'p' password = 'p' user = authenticate(request , username=username, password=password) if user is not None: return HttpResponse('the user exist') else: return HttpResponse('the user does not exist in database') i also checked the charset of the columns in the database and it was utf8mb4_general_ci -
Pycairo build failed as I tried upload django project to Railway
I have been trying to upload my django project to Railway but whenever i try to upload fro my github repo this is the stack error i get #10 27.27 copying cairo/__init__.py -> build/lib.linux-x86_64-cpython-310/cairo #10 27.27 copying cairo/__init__.pyi -> build/lib.linux-x86_64-cpython-310/cairo #10 27.27 copying cairo/py.typed -> build/lib.linux-x86_64-cpython-310/cairo #10 27.27 running build_ext #10 27.27 Package cairo was not found in the pkg-config search path. #10 27.27 Perhaps you should add the directory containing `cairo.pc' #10 27.27 to the PKG_CONFIG_PATH environment variable #10 27.27 No package 'cairo' found #10 27.27 Command '['pkg-config', '--print-errors', '--exists', 'cairo >= 1.15.10']' returned non-zero exit status 1. #10 27.27 [end of output] #10 27.27 #10 27.27 note: This error originates from a subprocess, and is likely not a problem with pip. #10 27.27 ERROR: Failed building wheel for pycairo #10 27.27 Failed to build pycairo #10 27.27 ERROR: Could not build wheels for pycairo, which is required to install pyproject.toml-based projects #10 27.27 #10 27.27 [notice] A new release of pip available: 22.3.1 -> 23.2.1 #10 27.27 [notice] To update, run: pip install --upgrade pip #10 27.27 [end of output] #10 27.27 #10 27.27 note: This error originates from a subprocess, and is likely not a problem with … -
Login Redirection Issue
When I log into my web application, it doesn’t redirect to the custom redirect page created instead it redirects to the default accounts/profile url in Django. Below are my codes: urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='myapp/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('phase1/', views.phase1_view, name='phase1'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login from django.contrib.auth import logout from django.conf import settings #Phases Details View @login_required def phase1_view(request): settings.LOGIN_REDIRECT_URL = '/myapp/phase1/' return render(request, 'myapp/phase1.html') #Logout View def logout_view(request): logout(request) return redirect('login') #Login View def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('phase1') else: return render(request, 'myapp/login.html', {'error_message': 'Invalid login credentials'}) else: return render(request, 'myapp/login.html') settings.py LOGIN_URL = 'login' login.html <form method="post" action="{% url 'login' %}"> {% csrf_token %} <div> <label>Username</label> <input type="text" id="username" name="username" class="text-input" required> </div> <div> <label>Password</label> <input type="password" id="password" name="password" class="text-input" required> </div> <button type="submit" id="submit" value="Login" class="primary-btn">Sign In</button> </form> I tried to add LOGIN_REDIRECT_URL = '/myapp/phase1/' in settings.py but it not worked. -
djongo(django + mongo) trouble with inspectdb, unable to inspectdb and import model
I am newbie to python and django, Using Django version: 4.1.10 and python version : 3.11.4 I have existing mongodb database so I am trying to import models in djongo (django + mongo) with inspectdb. But I keep getting following err which is mentioned here as well PS C:\Users\del\Downloads\splc\jango\splc1> python manage.py inspectdb Traceback (most recent call last): File "C:\Users\del\Downloads\splc\jango\splc1\manage.py", line 22, in <module> main() File "C:\Users\del\Downloads\splc\jango\splc1\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 936, in exec_module File "<frozen importlib._bootstrap_external>", line 1074, in get_code File "<frozen importlib._bootstrap_external>", line 1004, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed SyntaxError: source code string cannot contain null bytes What am I missing here, any help is really appriciated. -
How to perform AES on username and password in REACT and DJANGO Python
I have followed to encrypt username and password AES in React based on the below link https://www.code-sample.com/2019/12/react-encryption-decryption-data-text.html using crypto-js const encryptedUsername = CryptoJS.AES.encrypt(usernameWithoutSpaces, SECRET_KEY).toString(); const encryptedPassword = CryptoJS.AES.encrypt(values.password, SECRET_KEY).toString(); I have used the SECRET_KEY as 16byte code which I randomly generated. And used this key for both encrypt and decrypt. I have followed the decryption based on https://devrescue.com/python-aes-cbc-decrypt-example/ from Crypto.Cipher import AES from Crypto.Util.Padding import unpad import base64 def decrypt_view(request): encrypted_username = request.data['username'] # Replace with your encrypted username encrypted_password =request.data['password'] # Replace with your encrypted password print("22222222222222",encrypted_username) # secret_key = b'\xd4\xa5?\xa5\xcd\x95\xees_\t\xa5\x9eI\x9d\x81\x95' # Convert your secret key to bytes secret_key =b'53d7311e6f8f88c0bbc4a08bccd7e254' decrypted_username = decrypt_data(encrypted_username, secret_key) decrypted_password = decrypt_data(encrypted_password, secret_key) print('Decrypted Username:', decrypted_username) print('Decrypted Password:', decrypted_password) def decrypt_data(encrypted_data, key): try: cipher = AES.new(key, AES.MODE_CBC, iv=b'1234567890123456') decrypted_data = unpad(cipher.decrypt(base64.b64decode(encrypted_data)), AES.block_size) # print("&&&&&&&&&&&&&&",decrypted_data) return decrypted_data.decode('utf-8') except Exception as e: print("DDDDDDDDDDDDDDD",e) with this encryption done at frontend and at backend couldn't decrypt as Error which i got as Padding is incorrect. Padding is incorrect. I have also used cryptography module and fernet which is in python to perform decryption. hence it doesnt suite with crypto-js. -
New Django Developer unable to get "Hello World" to display on website instead of the default installed successfully page
I am following along with a Django tutorial to create my first website. Everything was working according to plan until I reached the step that involved the URL Patterns. Specifically it is the include() function that made this project come off the rails. When I reach this point in the tutorial I run the server on my localhost. The default Django installed successfully homepage is displayed instead of the "Hello World" text that is my tutorial index page. I have double checked that my code matches both the tutorial that I am following as well as the official Django tutorial but my results do not change. I have checked several solutions from stackoverflow but have been unable to resolve this problem. /first_project/first_project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("", include('first_app.urls')), path("admin/", admin.site.urls), ] first_project/first_project/settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "first_app", ] /first_project/first_app/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name = "index"), ] first_project/first_app/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello World") One of the suggestions on stack overflow was under first_project/first_project/urls.py to change … -
Background image in css is not found in Django using scss, webpack
I setup SCSS with webpack in Django. The only problem that I encounter in the setup is that background images in generated css file is not found by Django. This is the webpack.config.js const path = require('path'); const webpack = require('webpack'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { VueLoaderPlugin } = require("vue-loader"); module.exports = { entry: { main: './src/main.js', }, output: { path: path.resolve(__dirname, '../../backend/static/'), publicPath: '/', filename: '[name].js' }, devServer: { static: { directory: path.join(__dirname, '../../backend/static/'), }, port: 9000, historyApiFallback: true, }, module: { rules: [ { test:/\.scss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader', ] }, { test: /\.vue$/i, exclude: /(node_modules)/, use: { loader: "vue-loader", }, }, { test: /\.(js|jsx)$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: ["@babel/preset-env"], }, } }, { test: /\.html$/i, loader: "html-loader", }, { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, "css-loader", "style-loader"], }, { test: /\.(?:ico|gif|png|jpg|jpeg)$/i, type: 'asset/resource', }, { test: /\.(woff(2)?|eot|ttf|otf|svg|)$/, type: 'asset/inline', }, ] }, plugins: [ new VueLoaderPlugin(), new MiniCssExtractPlugin(), // new HtmlWebpackPlugin({ // template:"./src/index.html" // }), new webpack.DefinePlugin({ __VUE_OPTIONS_API__: true, __VUE_PROD_DEVTOOLS__: false }) ], resolve: { extensions: ['.js', '.jsx', '.scss', '.vue'], alias: { }, modules: [ path.resolve(__dirname, "../src/images/"), "../node_modules/" ], }, }; This is my Django Settings for static … -
payment integration in django
url = "https://api-gateway.sandbox.ngenius-payments.com/identity/auth/access-token" headers = { "Content-Type": "application/vnd.ni-identity.v1+json", "Authorization": f"Basic {settings.N_GENIUS_API_KEY}" } # Include the realmName in the body body = { "realmName": "Fenzacci" } response = requests.post(url, headers=headers, data=json.dumps(body)) print(response.text) if response.status_code == 200: return response.json().get('access_token') else: return None { "message" : "Not Found", "code" : 404, "errors" : [ { "message" : "Unable to find a tenant details.", "localizedMessage" : "Duplicate tenant name", "errorCode" : "realmNameNotAvailable", "domain" : "identity" } ] } I tried a lot of way but did not find a solution for that, I am so thankful for your response and answer to help me with that. -
Django scripts can't access files from docker volume
I add data folder (containing files with meta data) to the .dockerignore file. Because I don't want to weigh down my containers. don't want my containers to be too heavy. Since the datafolder contains huge files that need to bee read by the application. So I decided to mount a volume in my docker compose like below. And when I go inside the webcontainer I can see the file. And inside the container when I type /sigma/data/imports/dbm.csv I got the data. But when trying to read the file I goot this error : [Errno 2] No such file or directory: '/sigma/data/imports/dbm.csv' Am I missing ou misunderstood something? Docker compose file (an extract) web: container_name: web # image: aba2s/sigma build: context: . dockerfile: ./Dockerfile entrypoint: /sigma/docker-entrypoint.sh restart: unless-stopped env_file: - .env ports: - "8000:8000" depends_on: - db volumes: - ./data:/sigma/data View that read the file In settings.py file, I have this : IMPORTS_PATH = '/sigma/data/imports/' file_path = settings.IMPORTS_PATH + 'dbm.csv' df_import = pd.read_csv( file_path, sep=';', header=0, usecols=cols, index_col=False, on_bad_lines='skip', ) -
JS Appended Array in FomData not accessable in Django backend
In a django template i have this js script: const formData = new FormData(form); formData.append('taglist', JSON.stringify(selectedTagIds)); console.log(JSON.parse(formData.get('taglist'))) console.log(formData.get('title_raw')) form.submit() selectedTagIds is an array. The console logs it correctly. After submitting I can access every standard form field in the django view but not the "taglist". The field doesn't exist in the form. When I try to print it i get "None". What am I doing wrong? -
Django large file upload (.dcm)
After the user starts uploading files of 1-2 gb on a page in Django, I want the user to be able to navigate on other pages while the upload process continues. How can I do it? I can upload the files to the server with the chunk method and merge them in the back. However, this upload process is interrupted when I switch to other pages. I want this to continue without interruption. I tried to create a structure with Django channels and send files with the chunking method of dropzone.js, but I failed. Only string data was sent. I also could not convert the chunk .dcm data to base64. I did not try the celery method. I just searched for its possibility, but I could not find anything clear. autoProcessQueue: false, url: url, maxFiles: 100000000, maxFilesize: 99999, acceptedFiles: '.dcm', timeout: 9999999999, chunking: true, chunkSize: 2000000, clickable: "#dicomDropzone", parallelChunkUploads: false, retryChunks: true, retryChunksLimit: 5, forceChunking: true, init: function() { $('#CBCTUpload').click(function(){ myDropzone2.processQueue(); }) this.on("addedfile", function(file) { totalAddedFiles++; }); this.on("sending", function(file, xhr, formData) { formData.append('slug', parametre); }); } if request.method == 'POST': if 'file' not in request.FILES: return HttpResponse(status=500) file = request.FILES['file'] print("FILE", file.name) current_chunk = int(request.POST['dzchunkindex']) + 1 total_chunks = int(request.POST['dztotalchunkcount']) …