Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OpenCV opens camera at the first load, but if I refresh the page, it doesn't bring camera (can't open camera by index)
I have this Django project for Video-Streaming. So everything works perfectly fine on my system (MacOS). But here's what happens in Ubuntu 20.04: Works fine for the first loading If I refresh the page or go to other pages and come back again, the camera is not being opened by my app. This is the error: [ WARN:0] global /tmp/pip-req-build-ms668fyv/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video0): can't open camera by index This is Views.py import cv2 from django.http import HttpResponse, StreamingHttpResponse from django.shortcuts import render from django.views import View import threading class VideoStream(View): def __init__(self): cv2.destroyallwindows() self.camera = cv2.VideoCapture(0, cv2.CAP_V4L2) def __del__(self): self.camera.release() def get_frame(self): ret, frame = self.camera.read() if ret: _, jpeg = cv2.imencode(".jpg", frame) return jpeg.tobytes() else: # print('frame',frame) return None def generate(self): while True: frame = self.get_frame() if frame is not None: yield ( b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n\r\n" ) def get(self, request, *args, **kwargs): return StreamingHttpResponse( self.generate(), content_type="multipart/x-mixed-replace; boundary=frame" ) class StreamView(View): template_name = "stream.html" def get(self, request, *args, **kwargs): return render(request, self.template_name) This is video-stream.html <!DOCTYPE html> <html> <head> <title>Video</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <h1>Real-Time Video Stream</h1> <p>This is Paragraph</p> <img id="video-frame" src="" alt="Video Stream" /> <script> function updateFrame() { console.log("in update frame"); $('#video-frame').attr('src', '{% url … -
How to modify back button functionality in chrome in a website?
I have created a quiz website. So after submitting a quiz, it redirects me to the results page. But if i click back button it goes back to the last question. But I want it to take me back to the home page where all the list of available quizzes is seen. I am not getting any idea how to do it, so I could use some help. My project is a django project so I wanna know how can it be done using djnago? Anyways I am open to all answers -
KeyError in constance package used in Django
I am getting the following error when I try to run my debugger configuration on a Django project through a Docker container using Docker Compose. I can't find AUTO_END_TIMEDELTA_MINS anywhere on the web. Any idea what that might be? Traceback (most recent call last): 2023-08-21T18:03:17.443221106Z File "/usr/local/lib/python3.8/site-packages/constance/base.py", line 14, in __getattr__ 2023-08-21T18:03:17.443224978Z if not len(settings.CONFIG[key]) in (2, 3): 2023-08-21T18:03:17.443227740Z KeyError: 'AUTO_END_TIMEDELTA_MINS' -
Need to know if it is possible to develop log users in django?
I am developping a web application with django and want that admin should see all operations done by differents users in a log. Is it possible to do that please? i am trying to know the possibility if someone did that with django -
"ValueError: not enough image data" from Pillow when saving to a Django ImageField
I have a Django model like: class Website(models.Model): favicon = models.ImageField( null=False, blank=True, default="", width_field="favicon_width", height_field="favicon_height", ) favicon_width = models.PositiveSmallIntegerField(null=True, blank=True) favicon_height = models.PositiveSmallIntegerField(null=True, blank=True) I'm fetching a .ico file and saving it to the favicon field as a .png like this: import io import requests from django.core import files from .models import Website website = Website.objects.get(pk=1) response = requests.get("https://www.blogger.com/favicon.ico", stream=True) image_data = io.BytesIO(response.content) website.favicon.save("favicon.png", files.File(image_data)) Behind the scenes, Pillow successfully converts the ICO file to a PNG, and saves the file. But I then get an error. The traceback includes: # More here File /usr/local/lib/python3.10/site-packages/django/db/models/fields/files.py:491, in ImageField.update_dimension_fields(self, instance, force, *args, **kwargs) 489 # file should be an instance of ImageFieldFile or should be None. 490 if file: --> 491 width = file.width 492 height = file.height 493 else: 494 # No file, so clear dimensions fields. # Lots more here File /usr/local/lib/python3.10/site-packages/PIL/Image.py:804, in Image.frombytes(self, data, decoder_name, *args) 802 if s[0] >= 0: 803 msg = "not enough image data" --> 804 raise ValueError(msg) 805 if s[1] != 0: 806 msg = "cannot decode image data" ValueError: not enough image data So it can save the image but, I'm guessing, not get the width/height from the image to save. BUT, … -
Django "unable to open database file" after cleaning some stuff from my laptop
recently I've been cleaning up my laptop and I believe I have deletedsmth related to my database file in django, whenever I try to login/signup there is an error: OperationalError at /admin/login/ unable to open database file Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 4.2.2 Exception Type: OperationalError Exception Value: unable to open database file Exception Location: C:\Users\Mechta\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in execute Raised during: django.contrib.admin.sites.login Python Executable: C:\Users\Mechta\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.4 Python Path: ['C:\Users\Mechta\Documents\rasengan', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\Lib\site-packages'] I can provide info if u need more details I've read some other posts in here and watched some yt videos but nothing rly helped so I'm stuck -
Download file using DRF
I had written code to download file file_path = file_url FilePointer = open(file_path,"r") response = HttpResponse(FilePointer,content_type='application/msword') response['Content-Disposition'] = 'attachment; filename=NameOfFile' return response. How can I test this code using postman if actually a file gets download when i use this api While React JS code on the frontend is suitable for verifying file downloads, I'm interested in confirming the same using Postman. -
how to save data as null in database in Django forms
here is my problem "Do something in the input form so that the subject value does not need to be filled when sending and it is saved in the database without any input." it is an important task for me I'll be so grateful if you help me models.py from django.db import models # Create your models here. class Contact(models.Model): name = models.CharField(max_length=255) email = models.EmailField() subject = models.CharField(max_length=255) message = models.TextField() created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['created_date'] def __srt__(self): return self.name forms.py from django import forms from website.models import Contact class ContactForm(forms.ModelForm): subject = forms.CharField(required=False) class Meta: model = Contact fields = "__all__" views.py from django.shortcuts import render from django.http import HttpResponse from website.forms import ContactForm from django.contrib import messages def index_view(request): return render(request, "website/index.html") def about_view(request): return render(request, "website/about.html") def contact_view(request): if request.method == "POST": form = ContactForm(request.POST) request.POST._mutable = True request.POST['name'] = 'Anonymous' if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, "your ticket submited") else: messages.add_message(request, messages.ERROR, "your ticket did not submited") form = ContactForm() return render(request, "website/contact.html", {"form:form}) i try somethings in model but it didn't work -
Why am I getting a Bad Gateway Error sending bulk emails with Django
I have a need to send bulk emails, as much as 60 at a time, using an action in the Admin module. I do this by selecting certain cases and then running an admin action. Sometimes when I do this, not all 60 emails send. Sometimes they seem to go in batches of 20/30 and there could be a delay of a few hours between batches. This time I got an incomplete batch being sent and a 'Bad Gateway' error, with 8 emails not being sent. Those that what sent were sent twice. I can't see anything wrong with my code that would cause this. Any ideas would be greatly appreciated. I have the following Admin Action in my admin.py file: emailset=queryset.all().order_by('customer') for q in emailset: customer=q.customer email_to = q.customer.email html_content = render_to_string("accounts/email_template_staff_registration.html", {'q':q}) text_content = strip_tags(html_content) email = EmailMultiAlternatives( #subject "Staff Registration Email", #content text_content, #from settings.EMAIL_HOST_USER, # rec list [email_to], ['INSERT EMAIL ADDRESS FOR CC'] ) email.attach_alternative(html_content, "text/html") email.send() updated=len(queryset) self.message_user(request, ngettext( '%d Staff Registration Email was successfully sent.', '%d Staff Registration Emails were successfully sent.', updated, ) % updated, messages.SUCCESS) send_staff_reg_email.short_description="Send staff registration email" ``` -
Django docker container with nginx and extern database from azure
I have a django docker container. And I try to deploy it. I am using a database service from Azure. with url: db.postgres.database.azure.com" And I am using reverse proxy NGINX for the server. So I have folder named proxy within a docerfile: FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ touch /etc/nginx/conf.d/default.conf && \ chown nginx:nginx /etc/nginx/conf.d/default.conf && \ chmod +x /run.sh VOLUME /vol/static USER nginx CMD ["/run.sh"] and default.conf.tpl: server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass 8000:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } And in the root folder of the app I have a file: docker-compose-deploy.yml: version: "3.9" services: app: build: context: . dockerfile: Dockerfile.prod restart: always volumes: - static-data:/vol/web environment: - DJANGO_ALLOWED_HOSTS={DJANGO_ALLOWED_HOSTS} env_file: - ./.env.prod proxy: build: context: ./proxy restart: always depends_on: - app ports: - 8000:8000 volumes: - static-data:/vol/static volumes: static-data: and .env.prod file: DEBUG=0 SECRET_KEY="+)d)&d0^&0xda+s%1o(&r3+24)x#i^bk8p8r)@jl_q2=%usxw=" DB_NAME="name" DB_USER="user" DB_PASSWORD="pass" DB_HOST="db.postgres.database.azure.com" DJANGO_ALLOWED_HOSTS="127.0.0.1" and part of settings.py file: import os import dotenv dotenv.read_dotenv() from pathlib import Path from os import environ import dotenv # Build paths inside the project like this: BASE_DIR … -
Adding google fonts in django-quill-editor
I'm working with django-quill-editor and I want to add a custom google font. However I could not add it. I just want to know that is it possible to add custom google fonts in django-quill-editor. I tried like this but it didn't work. QUILL_CONFIGS = { 'default':{ 'theme': 'snow', 'modules': { 'syntax': True, 'toolbar': [ [ {'font': ['Montserrat']}, {'header': []}, {'align': []}, 'bold', 'italic', 'underline', 'strike', 'blockquote', {'color': []}, {'background': []}, ], ['code-block', 'link'], ['clean'], ] } } } -
Finding Duplications with Pandas Pivot Table Works The First Time, Fails Second Time Forward
We have an xlsx file that we process into a dataframe to gather duplications values and count of duplications def duplicationCount(table_file_path, targetColumns): dfTable = pd.read_excel(io=table_file_path, sheet_name='Sheet1', skiprows=0) dfTable.columns = dfTable.columns.str.strip("'") res = dfTable.pivot_table(index=targetColumns, aggfunc='size') res.reset_index() res.rename(columns={'Unnamed: 0': 'no of dups'}, inplace=True) res.index.name = 'index' res = res[res['no of dups'] >= 2] targetColumns.extend(['no of dups']) res = res.filter(targetColumns).values.tolist() return res This works well the first time with output containing for example: account year no of dups 10301 2022 2 42334 2022 2 but running the same code with the same file the second time we get: Traceback (most recent call last): File "E:\Programs\XX\backend\app\views.py", line 265, in app_process_text_file results['DuplicationReportResults'] = duplicationCount(tables_file_paths[0], dupsFindingTargets) File "E:\Programs\XX\backend\app\functions.py", line 92, in duplicationCount res = dfTable.pivot_table(index=targetColumns, aggfunc='size') File "E:\Programs\XX\venv\lib\site-packages\pandas\core\frame.py", line 8044, in pivot_table return pivot_table( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\reshape\pivot.py", line 95, in pivot_table table = __internal_pivot_table( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\reshape\pivot.py", line 164, in __internal_pivot_table grouped = data.groupby(keys, observed=observed, sort=sort) File "E:\Programs\XX\venv\lib\site-packages\pandas\core\frame.py", line 7718, in groupby return DataFrameGroupBy( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\groupby\groupby.py", line 882, in __init__ grouper, exclusions, obj = get_grouper( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\groupby\grouper.py", line 882, in get_grouper raise KeyError(gpr) KeyError: 'no of dups' -
What's the best way to implement JWT authentication with multiple clients?
We currently use Djoser (with simplejwt), which has served us well. The only OAuth clients we had so far have been frontend apps. However, we now have to add access to some external services. There is no appetite to have separate gatekeeper proxy. This will need longer token life, etc and the simple_jwt is no longer the best solution. DRF website has a long list of third party libraries, which is great to have the choice, but makes the choice harder. Which of these packages, or another one that's not listed there, is a fairly easy replacement for Djoser? Ideally, it would be something which doesn't require us to write new views, etc for everything. -
My ckeditor-uploaded image doesn't show up in the post unless I restart the django app from cpanel
`My ckeditor uploaded image doesn't show up unless I restart the django app from cpanel my ckeditor-imported post page works fine in local server, BUT in the production server after i upload an image to server **FIRST **image doesnt in appear post layout (it used to in local server) in local server image would show up here in editor i used to have the image here in the editor it doesn't appear in my post neither... ....unless i restart it from cpanel after i restarted the app from cpanel, it started to work fine i have the following settings.py code: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'x' DEBUG = False ALLOWED_HOSTS = ['cozumdefteri.com'] INSTALLED_APPS = [ 'gonderiyaz.apps.GonderiyazConfig', 'ckeditor', 'ckeditor_uploader', 'mebsci.apps.MebsciConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') CKEDITOR_UPLOAD_PATH = 'static/uploads/' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'cozumdefteri.urls' STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'cozumdefteri.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = … -
Ubuntu to windows django project
So I have developed several projects in Ubuntu. So I get the projects set up in Windows and run them; they are running properly, but I am facing a problem with the static files, that is, the CSS, showing up when I run the web applications. I have inspected the webapps, and it shows that the CSS and static files are being fetched and served (200 code). So what is the issue, and how can I solve it? -
how to reverse queryset without getting error: AttributeError: 'reversed' object has no attribute 'values'
I want to reverse the order of the following queryset, but I get the error AttributeError: 'reversed' object has no attribute 'values'. I believe this is because of the reversed_instances.values(). Without changing reversed_instances.values(), how can I reverse the order of instances? Thank you, and please leave a comment at the bottom. def view(request, pk): instances = Calls.objects.filter(var=var).order_by('-date')[:3] reversed_instances = reversed(instances ) return JsonResponse({"calls":list(reversed_instances.values())}) -
Django and ReactJS Project: Module parse failed: Unexpected token (14:12) You may need an appropriate loader to handle this file type
I know there's a lot of similar questions out there but I've tried to do what was suggested and I just can't seem to solve this error. So I'm working on a project using Django and ReactJS. I am using Webpack and Babel to connect front end and back end. I keep getting this error when I run the frontend: ERROR in ./src/components/App.js 14:12 Module parse failed: Unexpected token (14:12) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | return ( > <div className="App"> | <Router> | <Navbar /> | <Routes> @ ./src/index.js 1:0-35 I will attach my webpack.congig file and babel.config file. Any help would be appreciated! Webpack.config.js const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, // { // test: /\.(js|jsx)$/, // include: path.resolve(__dirname, 'src'), // exclude: /(node_modules|bower_components|build)/, // use: ['babel-loader'] // } ], }, resolve: { extensions: ['*', '.js', '.jsx'] }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ] }, … -
Loading of GDAL library impossible after an upgrade
I have a Python environment with Django 3 that has to use GDAL (because the DB engine I use is django.contrib.gis.db.backends.postgis). After an upgrade of GDAL (from 3.6.4_6 to 3.7.1_1), I have this exception on any command to run the django project : File "~/.pyenv/versions/3.8.9/lib/python3.8/ctypes/__init__.py", line 373, in __init__ self._handle = _dlopen(self._name, mode) OSError: dlopen(/usr/local/lib/libgdal.dylib, 0x0006): Symbol not found: __ZN3Aws6Client19ClientConfigurationC1Ev Referenced from: <FA8C3295-2793-3C69-A419-16C41753696B> /opt/homebrew/Cellar/apache-arrow/12.0.1_4/lib/libarrow.1200.1.0.dylib Expected in: <BDB1F1E3-0BE9-3D7D-A57E-9D9F8CAD197A> /opt/homebrew/Cellar/aws-sdk-cpp/1.11.145/lib/libaws-cpp-sdk-core.dylib I've managed to isolate the problem in a fresh python environment with only loading the GDAL library : from ctypes import CDLL; CDLL("/usr/local/lib/libgdal.dylib"). Note, I'm on a Mac (CPU M2 Pro), I've installed GDAL and all its dependancies via brew. I've tried reinstalling it from fresh but it didn't change a thing and I've also tried with different python versions. -
My drop-down not showing up in my templates - django
i'm trying to make a nested drop-down with dajngo-mptt for a category section in mt project the code is working and i can see my codes in inspect but its not showing in my template can anybody help??? my template: <div class="dropdown"> <ul class="dropdown-menu"> {% recursetree categories %} <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ node.name }} </button> <li {% if not node.is_leaf_node %}class="dropdown-submenu"{% endif %}> <a class="dropdown-item {% if not node.is_leaf_node %}dropdown-toggle{% endif %}" href="{% if node.is_leaf_node %}{{ node.get_absolute_url }}{% endif %}" {% if not node.is_leaf_node %}role="button" data-bs-toggle="dropdown" aria-expanded="false"{% endif %}> {{ node.name }} {% if not node.is_leaf_node %}<span class="dropdown-caret"></span>{% endif %} </a> {% if not node.is_leaf_node %} <ul class="dropdown-menu"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> veiws.py class HomePage(View): def get(self, request, ): postss = Post.objects.all() categories = Category.objects.all() form = CategoryForm() return render(request, 'home/index.html', {'postss': postss, 'categories': categories, 'form': form}) and i have this js in my base.html document.addEventListener('DOMContentLoaded', function() { var dropdownSubmenus = [].slice.call(document.querySelectorAll('.dropdown-submenu')); dropdownSubmenus.forEach(function(submenu) { submenu.addEventListener('mouseenter', function() { this.querySelector('.dropdown-menu').classList.add('show'); }); submenu.addEventListener('mouseleave', function() { this.querySelector('.dropdown-menu').classList.remove('show'); }); }); }); i'm added to my code and added button to show it but it's not showed up what can i do? -
How to get the value from an Orderable from a Wagtail Page, and then call a function that will return a value based on the input of the Orderable?
I have a Django/Wagtail project. I have modified the HomePage in models.py and then in the Wagtail CMS, I populated the newly created fields of my homepage. Here is how my models.py looks like: from django.db import models from wagtail.core.models import Page from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel from wagtail.core.fields import RichTextField from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.core.models import Orderable from wagtail.images.edit_handlers import ImageChooserPanel from django.shortcuts import render class HomePage(Page): templates = "templates/home/home_page.html" background_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) hero_title = models.CharField(max_length=255, blank=True, null=True) form_placeholder_text = models.CharField(max_length=255, blank=True, null=True) form_cta_button_text = models.CharField(max_length=255, blank=True, null=True) hero_title_2 = models.CharField(max_length=255, blank=True, null=True) hero_title_3 = models.CharField(max_length=255, blank=True, null=True) description = RichTextField(blank=True, null=True) hero_title_4 = models.CharField(max_length=255, blank=True, null=True) content_panels = Page.content_panels + [ MultiFieldPanel([ ImageChooserPanel('background_image'), FieldPanel('hero_title'), FieldPanel('form_placeholder_text'), FieldPanel('form_cta_button_text'), InlinePanel('slider_items', label="Slider Items"), ], heading="Hero Section 1"), MultiFieldPanel([ FieldPanel('hero_title_2'), InlinePanel('card_locations', label="Card Locations"), ], heading="Hero Section 2"), MultiFieldPanel([ FieldPanel('hero_title_3'), FieldPanel('description'), ], heading="Hero Section 3"), MultiFieldPanel([ FieldPanel('hero_title_4'), InlinePanel('column_one_items', label="Column One Items"), InlinePanel('column_two_items', label="Column Two Items"), InlinePanel('column_three_items', label="Column Three Items"), ], heading="Hero Section 4"), ] class SliderItem(Orderable): page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='slider_items') slider_text = models.CharField(max_length=255, blank=True, null=True) slider_link = models.URLField(blank=True, null=True) panels = [ FieldPanel('slider_text'), FieldPanel('slider_link'), ] class CardLocation(Orderable): page = ParentalKey(HomePage, on_delete=models.CASCADE, … -
Nginxproxymanager doesn't serve mediafiles in django
I am using nginxproxymanager https://nginxproxymanager.com/ and can't configure it to serve media files uploaded by users in django app. This is my docker compose file: version: "3.9" services: api: &api build: context: . dockerfile: ./docker/production/django/Dockerfile command: /start image: shop_api volumes: - static_volume:/app/staticfiles - media_volume:/app/mediafiles env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres depends_on: - postgres - redis networks: - reverseproxy_nw postgres: image: postgres:15-bullseye volumes: - production_postgres_data:/var/lib/postgresql/data env_file: - ./.envs/.production/.postgres networks: - reverseproxy_nw redis: image: redis:7-alpine networks: - reverseproxy_nw celery_worker: <<: *api image: shop_api_celery_worker command: /start-celeryworker networks: - reverseproxy_nw flower: <<: *api image: shop_api_flower command: /start-flower volumes: - flower_data:/data networks: - reverseproxy_nw networks: reverseproxy_nw: external: true volumes: static_volume: {} media_volume: {} production_postgres_data: {} flower_data: {} this is nginxproxymanager configs enter image description here MEDIA_URL = "/mediafiles/" MEDIA_ROOT = str(ROOT_DIR / "mediafiles") when i try to get image https://{domain}/mediafiles/my-img.png it just returns 404 error, i checked mediafiles folder inside docker container and it has that file, but when i try to request it, it gives 404 :( -
Pass variables as arguments to Django custom tag in view
I have a custom tag in Django project: class ExampleNode(template.Node): def __init__(self, nodelist, header_copy='', paragraph_copy='', ): self.nodelist = nodelist self.header_copy = header_copy self.paragraph_copy = paragraph_copy def render(self, context): template = 'example.html' context = { 'elements': self.nodelist.render(context), "header_copy": self.header_copy, "paragraph_copy": self.paragraph_copy, } return render_to_string(template, context) @register.tag def example_component(parser, token): try: tag_name, header_copy, paragraph_copy = token.split_contents() except ValueError: raise TemplateSyntaxError("%r takes two arguments" % token.contents.split()[0]) nodelist = parser.parse(('endexample_component',)) parser.delete_first_token() return ExampleNode(nodelist, header_copy, paragraph_copy) And the view of the component is: <div> <h1>{{ header_copy }}</h1> <p>{{ paragraph_copy }}</p> </div> <div>{{ elements }}</div> Usage: {% with header_copy='Lorem ipsum dolor sit amet' paragraph_copy='Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.' %} {% example_component header_copy paragraph_copy %} <div>ex1</div> <div>ex2</div> {% endexample_component %} {% endwith %} And the issue is that what I am receiving in view is header_copy and paragraph_copy instead of Lorem ipsum. Only passing actual primitive value works. Maybe there is a better way to receive those args and parse them? -
understanding of urlpatterns in urls.py of Django App
Problem: When we try to add the data to the database. So, the request will always come to this URL starting with the project-level directory, todo_main. So here, we will create a pattern. path('todo/', include('todo.urls')), This path will forward the request to todo. URLs. from django.urls import path from .import views urlpatterns =[ path('addTask/', views.addTask, name='addTask'), ] So whenever we send a request to add a task, then the corresponding views.addTask should run, which will be a task. Questions: I try to understand my best what is the meaning or purpose of addTask. Can we write another word instead of it? -
Django path converter not converting value in path
I have an app that should be able to take a field's value in lower and uppercase. The url below should work http://localhost:8000/app/family=Araceae/ but fail if value is araceae. I followed the official documentation but it's not working. path('app/family=<str:family>/', views.SpeciesDetail_family.as_view(), name='family') I made a converter to convert the value to lower case if it's in uppercase but is returning 404 saying URL does not match the patterns below admin/ app/family=<value:family>/ [name='family'] app/family=<value:family><drf_format_suffix:format> [name='family'] urls.py from django.urls import path, register_converter from rest_framework.urlpatterns import format_suffix_patterns from app import converters, views register_converter(converters.convert_value_to_lowercase, 'value') urlpatterns = [path('app/family=<value:family>/', views.SpeciesDetail_family.as_view(), name='family')] urlpatterns = format_suffix_patterns(urlpatterns) converters.py class convert_value_to_lowercase: regex = '[A-Z]' def to_python(self, value): value = value.lower() return value def to_url(self, value): return value -
Dockerise Django with proxy server NGINX
I have dockerised a django application. And now I try to deploy the app to a live server. So I am using the NGINX reversed proxy server. I have a folder name called proxy within a dockerfile: FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_HOST=app ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ touch /etc/nginx/conf.d/default.conf && \ chown nginx:nginx /etc/nginx/conf.d/default.conf && \ chmod +x /run.sh VOLUME /vol/static USER nginx CMD ["/run.sh"] and a default.conf.tpl file: server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } And a run.sh script: #!/bin/sh set -e envsubst < /etc/nginx/default.conf.tpl > /etc/nginx/conf.d/default.conf nginx -g 'daemon off;' and docker-compose-deploy.yml looks: version: "3.9" services: app: build: context: . dockerfile: Dockerfile.prod restart: always volumes: - static-data:/vol/web environment: - DJANGO_ALLOWED_HOSTS={DJANGO_ALLOWED_HOSTS} env_file: - ./.env.prod proxy: build: context: ./proxy restart: always depends_on: - app ports: - 8000:8000 volumes: - static-data:/vol/static volumes: static-data: part of my settings.py file looks like: import os import dotenv dotenv.read_dotenv() from pathlib import Path from os import environ import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR …