Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
socialaccount + mfa: how to bypass the mfa code form?
on an older version of django-allauth (0.61.1) I used totp for the two-auth. Now I've udpdated to django-allauth[mfa]==65.3.0 and I have an issue by using the socialaccount auth. Before I used a customer AccountAdapter to check if the user coming from a microsoft: class AccountAdapter(DefaultAccountAdapter): def has_2fa_enabled(self, user): """Returns True if the user has 2FA configured.""" return user.has_2fa_enabled if user.is_authenticated else False def login(self, request, user): # Require two-factor authentication if it has been configured. if ( self.has_2fa_enabled(user) and not request.path == "/auth/microsoft/login/callback/" ): redirect_url = reverse("two-factor-authenticate") # Add GET parameters to the URL if they exist. if request.GET: redirect_url += "?" + urlencode(request.GET) raise ImmediateHttpResponse(response=HttpResponseRedirect(redirect_url)) return super().login(request, user) Now, with the new update, the 2FA code is asked AFTER the super().login How can I bypass the MFA code? I've checked the documentation and I see only "is_mfa_enabled" in the DefaultMFAAdapter but this is not nice as it will just say False on is_mfa_enabled but not only change if the app asks the code or not. Is there any other way for that? -
Why is my @import in CSS not working when importing other CSS files?
I'm building a Django project and trying to organize my CSS files by importing them into a single index.css. However, the styles from the imported files are not being applied when I include only index.css in my base.html. Here's what I've done: File Structure: static/ ├── css/ │ ├── index.css │ ├── footer.css │ └── courses/ │ └── courses.css index.css: @import url("footer.css"); @import url("courses/courses.css"); .verticalSpace { padding-top: 100px; } base.html: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="{% static 'css/index.css' %}"> </head> <body> {% block content %} {% endblock %} </body> </html> Observations: If I directly include footer.css or courses/courses.css in the HTML, the styles work. <link rel="stylesheet" href="{% static 'css/courses/courses.css' %}"> The styles do not work when I rely on @import in index.css. Questions: Why are the imported styles not applying when using @import in index.css? Is there a better way to structure CSS imports in Django to only link index.css in the HTML? Could this issue be related to Django's STATIC_URL or how @import resolves paths? What I've Tried: Checked that static files are correctly set up in settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] Verified that the CSS files load correctly when linked directly. Tried … -
Circular import in Django
Im getting this error : does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import whenever i try python manage.py runserver app urls.py from django.urls import path from . import views urlpatterns = [ path ('', views.index, name='index'), ] project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] app Views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('<h1> Hello man</h1>') Im using Django 4.1, and Python 3.10.10, I also tried this with python 3.12 and Django 5.1.4, still error persisted. Without this particular line of code below in the parent app, the program runs fine. path('', include('myapp.urls')), but when I include the above line of code I get the following error: "does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import." I tried changing python environments, directories, rewriting the code and trying out in different python and django versions … -
Issues Importing CSV Data in Django Custom Management Command (DictReader Parsing Error)
Hi everyone, I'm working on a Django project where I need to import questions from a CSV file into my database using a custom management command. However, I'm facing an issue with parsing the CSV rows. Here’s what I’m doing: I’m using csv.DictReader to read the CSV file. My CSV file includes columns like subject, topic, difficulty_level, text, options, correct_option, and image. Here’s a sample of my CSV: subject,topic,difficulty_level,text,options,correct_option,image Physics,Thermodynamics,2,"Calculate ( W = P \cdot \Delta V ) for ( P = 100 , kPa ).","{""A"":""100 J"",""B"":""200 J"",""C"":""300 J"",""D"":""400 J""}","A","question_images/thermo_diagram.png" Math,Calculus,3,"Evaluate ( \int_0^1 x^2 dx ).","{""A"":""1/2"",""B"":""1/3"",""C"":""1/4"",""D"":""1/5""}","B","" Here’s the issue I’m encountering: When I run my management command, DictReader doesn’t seem to parse the rows correctly. I get errors like: javascript Copy code Error importing question: Unknown - 'subject' Debugging shows that the entire row is being read as a single key-value pair, rather than splitting into individual fields. I’ve tried: Ensuring the CSV file is UTF-8 encoded. Adding debugging to confirm the raw content of the CSV. Here’s my current code snippet for reading the CSV: python Copy code with open(csv_file, newline='', encoding='utf-8-sig') as file: reader = csv.DictReader(file) for row in reader: print("Parsed Row:", row) # Debugging What could be … -
how to render the content in the wagtail page especially listblock content
this my model file in which i define cards to the wagtail admin from wagtail.models import Page from wagtail.fields import StreamField from wagtail.admin.panels import FieldPanel from strems import Blocks class TestPage(Page): """Page for testing card block rendering.""" template = "strems/test.html" cards = StreamField( [("cards", Blocks.cardblocks())], blank=True, null=True, ) content_panels = Page.content_panels + [ FieldPanel("cards"), ] class Meta: verbose_name = "Test Page" verbose_name_plural = "Test Pages" this is my block.py in which i specify my list block in the strems app class cardblocks(StructBlock): title =CharBlock(required=True,help_text="Add text here") cards=ListBlock( StructBlock( [ ("image", ImageChooserBlock(require=True)), ("title",CharBlock(required=True,max_length=23)), ("text",TextBlock(required=True,max_length=50)), ("button_page",PageChooserBlock(required=False)), ("button_url",URLBlock(required=False)), ], ) ) template = "strems/card_block.html" class Meta: icon = "placeholder" label = "blockcards" ad also this is my html template for render the content {% extends "base.html" %} {% load wagtailcore_tags %} {% load wagtailimages_tags%} {% block content %} <div class="container"> <div class="container"> <h1>{{ self.title }}</h1> <div class="row"> {% for card in self.cards %} <div class="card col-md-4" style="width: 18rem; margin: 10px;"> {% if card.image %} <img src="{{ card.image.url }}" class="card-img-top"> {% endif %} <div class="card-body"> <h5 class="card-title">{{ card.title }}</h5> <p class="card-text">{{ card.text }}</p> {% if card.button_page %} <a href="{{ card.button_page.url }}" class="btn btn-primary">Go to {{ card.button_page.title }}</a> {% elif card.button_url %} <a href="{{ card.button_url … -
"Right" way to define helper functions for Django models' Meta classes
I'm trying to simplify a very verbose and repetitive Check constraint for a model, whose logic is currently very hard to parse, factoring out and aptly renaming the repetitive parts. Basically I want to turn this (simplified and abstracted snippet): class MyModel(models.Model): class Meta: constraints = [ models.CheckConstraint( check = ( ( models.Q(foo = True) & ( ( models.Q(field1 = 'X') & models.Q(field2 = 'Y') & models.Q(field3 = 'Z') ) | ( models.Q(field4 = 1) & models.Q(field5 = 2) & models.Q(field6 = 3) ) ) ) | ( models.Q(foo = False) & ( ( models.Q(field1 = 'X') & models.Q(field2 = 'Y') & models.Q(field3 = 'Z') ) | ( models.Q(field4 = 4) & models.Q(field5 = 5) & models.Q(field6 = 6) ) ) ) ), name = 'foo', ), ] Into this: class MyModel(models.Model): class Meta: constraints = [ models.CheckConstraint( check = ( ( models.Q(foo = True) & ( condition1 | condition2 ) ) | ( models.Q(foo = False) & ( condition1 | condition3 ) ) ), name = 'foo', ), ] What I've tried / thought of trying: Factoring out the conditions, both as attributes and methods in Meta itself; that didn't work: TypeError: 'class Meta' got invalid attribute(s): condition1,condition2,condition3; Factoring … -
How to display multiple lines of text in django admin for Headers?
Similar questions that have already been asked are for data fields like in Here and Here But how to split the header in multiple lines? Considering a Django app with model and admin setup like this: models.py from django.db import models class TaskItem(models.Model): group = models.ForeignKey(TaskGroup, on_delete=models.CASCADE) title = models.CharField(max_length=32, null=False, blank=False) description = models.CharField(max_length=45, null=False, blank=False) reward = models.IntegerField(default=1000, null=False, blank=False) admin.py class TaskItemAdmin(admin.ModelAdmin): list_display=['title', 'group', 'reward'] list_filter=('group',) How can I rename headers to Task Title, Task Group and Task Reward with line breaks? -
How to update a list of To-Do items with checkboxes and save changes using React and Django?
I am trying to update a list of To-Do items using React for the frontend and Django for the backend. Each item has a checkbox to mark it as complete or incomplete. When I click the "Save" button, I want the updated data to be sent to the backend via a PUT request. However, I am facing issues with updating the items properly. Here’s my React handleSave function that triggers the PUT request: const handleSave = async (e) => { e.preventDefault(); console.log('handleSave called'); const updatedItems = items.map((item) => { const checkbox = e.target[`c${item.id}`]; console.log(`Processing item id ${item.id}, checkbox value:`, checkbox?.checked); return { id: item.id, todolist: 1, text: item.text, complete: checkbox ? checkbox.checked : false, duration: item.duration, }; }); try { console.log('Payload to send:', updatedItems); const response = await axios.put( `${import.meta.env.VITE_API_URL}/todo-items/1`, // Update the endpoint if needed updatedItems, { headers: { 'Content-Type': 'application/json' }, // Set proper headers } ); console.log('Items updated successfully:', response.data); } catch (error) { console.error('Error updating items:', error.message, error.response?.data); } }; Here’s the Django view handling the request: @api_view(['GET', 'PUT']) def todo_items(request, id): try: ls = ToDoList.objects.get(id=id) except ToDoList.DoesNotExist: return Response({"error": "List not found"}, status=404) if request.method == 'GET': incomplete_items = ls.item_set.filter(complete=False) complete_items = ls.item_set.filter(complete=True) items = … -
Frontend React(next.js) Backend (DJango) and Database (PostGreSQL)
I am working on a small project with this stack Frontend React(next.js) ==> Backend (Django) ==> Database (PostgreSQL). Please advise if this is ok. donor management system (dms) Thanks & Regards Nawaz Mohammed -
Annotate multiple values as JSONObject - parse datetime
I'm annotating my QuerySet as follows, using JSONObject, to obtain multiple fields from Scan: MyModel.objects.annotate( myscan=Subquery( Scan.objects .all() .values(data=JSONObject( id='id', nin='nin', datetime='datetime') )[:1] ) ) I want to get a proper datetime representation though, somehow. When I try to use myscan.datetime, I get the string representation (e.g. datetime': '2024-12-31T09:19:30.221953+00:00. How can I either return the datetime object itself (instead of a string; assuming this is impossible when using JSONObject) or alternatively do a strptime() before returning the string as part of the JSON? Obviously I could parse the string, convert to datetime and then do strptime() again, but that seems like a dirty solution. Any suggestions? -
Django - javascript - ajax does not work with javascript created lines
I have three classes lets say, class Item(models.Model): id = models.AutoField(primary_key=True) # Explicitly define the id column as the primary key itemref = models.IntegerField(blank=True, null=True) code = models.CharField(max_length=150, db_collation='Turkish_CI_AS', blank=True, null=True) tanimlama = models.CharField(max_length=150, db_collation='Turkish_CI_AS', blank=True, null=True) itemname = models.CharField(max_length=150, db_collation='Turkish_CI_AS', blank=True, null=True) class SAFiche(models.Model): nothing important class SALine(models.Model): safiche = models.ForeignKey(SAFiche, on_delete=models.CASCADE) item = models.ForeignKey('accounting.Item', on_delete=models.CASCADE) In views, I have ajax for autocomplate: def item_autocomplete(request): query = request.GET.get('q', '') items = Item.objects.filter( Q(code__icontains=query) | Q(itemname__icontains=query) | Q(tanimlama__icontains=query) )[:10] # Limit to 10 results results = [] for item in items: label = f"{item.code or ''} - {item.itemname or item.tanimlama or ''}" results.append({ 'id': item.id, 'label': label.strip(' -'), }) return JsonResponse(results, safe=False) I properly adjusted rest. This is my forms: class SALineCreateForm(forms.ModelForm): urun_search = forms.CharField( label="Ürün Ara", required=False, widget=forms.TextInput(attrs={ 'placeholder': 'Ürün kodu veya adı...', 'class': 'item-search-input border rounded p-2 w-full', 'autocomplete': 'off' }) ) class Meta: model = SALine fields = [ 'urun', 'miktar' ] widgets = { 'urun': forms.HiddenInput(), 'miktar': forms.NumberInput(attrs={'class': 'w-full form-input rounded-md'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # If editing an existing line, fill the search box with the item name if getattr(self.instance, 'urun_id', None): self.fields['urun_search'].initial = str(self.instance.urun) SALineCreateFormSet = inlineformset_factory( SAFiche, SALine, form=SALineCreateForm, extra=1, … -
React, Django. Gunicorn, nginx , docker setup for production ready and not ablet to server static files for both frontend and backend
This is the current project director for my project as of now Project/ │── .env ├── docker-compose.yml # Docker Compose configuration file │ ├── Frontend/ # React Frontend (Client-side) │ ├── Dockerfile # Dockerfile for React app build │ ├── package.json # React package file │ ├── public/ # Public assets for React │ ├── src/ # React source code │ ├── build/ # React build output (this is where `npm run build` │ ├── nginx.conf └── Backend/ # Django Backend (Server-side) ├── Dockerfile # Dockerfile for Django app build ├── manage.py # Django manage.py file ├── Backend/ # Django application code (models, views, etc.) ├── requirements.txt ├── static/ # Static files (collected by `collectstatic`) ├── media/ # Media files (user-uploaded files) └── .dockerignore # Docker ignore file i have this directory structure where i have 2 folders for backend and front end each is build with Django and react respectively and i have the nginx file in the frontend directory to copy the first build in the frontend container but the thing is that i also share the same volume with the django also but nginx is not ablet to server sttic files to django as well get 404 … -
Django Vercel Deployment Issue | 500: INTERNAL_SERVER_ERROR | ModuleNotFoundError: No module named 'distutils'
I have been trying to deploy a Django App on vercel, it is getting deployed but the website is not working says "This Serverless Function has crashed" Requirements.txt Django==3.1.12 djongo==1.3.7 dnspython==2.7.0 pymongo==3.11.4 psycopg2-binary~=2.9.6 setuptools==75.7.0 vercel.json { "builds": [{ "src": "inventory_management/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }], "routes": [ { "src": "/(.*)", "dest": "inventory_management/wsgi.py" } ] } The error says, from distutils.version import LooseVersion ModuleNotFoundError: No module named 'distutils' Tried adding setuptools in requirements.txt but still the same issue -
social_core.exceptions.MissingBackend: Missing backend "google-oauth2" entry in Django with Google OAuth2
I'm working on integrating Google OAuth2 in my Django REST Framework project using django-rest-framework and social-django. However, when I try to authenticate using the endpoint: GET /api/o/google-oauth2/?redirect_uri=http://localhost:3000/auth/google I get the following error: social_core.exceptions.MissingBackend: Missing backend "google-oauth2" entry What could be causing the Missing backend "google-oauth2" entry error? Am I missing any configuration, or could there be an issue with the library versions? Any help or guidance would be appreciated. Added the following to my settings.py: AUTHENTICAION_BACKEN,DS =[ 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.facebook.FacebookOAuth2', ] SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'openid', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] The redirect_uri (http://localhost:3000/auth/google) matches the one registered in the Google API Console. -
Django annotation from different sources
I'm trying to build following annotation, essentially looking up the nin field from a person either from the IDcard or from the Person model. .annotate( checkins_scan=Scan.objects.filter(models.Q(nin=OuterRef("person__idcard__nin") | models.Q(national_number=OuterRef("person__nin"))) .values( data=JSONObject(id="id", nin="nin", datetime="datetime") )[:1] ) However, I get following error: NotImplementedError: Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations. Looks like I'll need bitor(), but I'm not getting any further with the basic examples I'm finding (e.g. documentation here). When I try to work with F() I get TypeError: F.__init__() got an unexpected keyword argument 'nin'. Any clues on how to properly do this? -
VSCode Test Explorer hangs despite no errors in the output & all tests being collected (in the output)
I have been having a lot of issues with Test Explorer in VSCode. It has been working fine up until last week. I was writing new tests and clicked "Refresh Tests" and then it suddenly (and pretty randomly) stopped working - specifically it "discovers" tests forever. And that is despite the fact that the output shows that the tests seem to be discovered correctly in the output window: The tests are also all passing if I run them with standard pytest terminal command: My directory structure is as follows: application ├── backend │ ├── src | ├── |── __init__.py | ├── |── manage.py | ├── |── app1 | ├── |── ├── __init__.py | ├── |── ├── folder1 | ├── ├── ├── ├── __init__.py | ├── |── ├── ├── views.py | ├── |── ├── ├── class1.py | ├── |── ├── ├── class2.py | ├── ├── ├── ├── tests | ├── ├── ├── ├── ├── __init__.py | ├── ├── ├── ├── ├── test_class1.py | ├── ├── ├── ├── ├── test_class2.py | ├── ├── ├── ├── ├── test_views.py | ├── |── ├── folder2 | ├── ├── ├── ├── __init__.py | ├── |── ├── ├── views.py | ├── |── ├── ├── class1.py | ├── … -
How to dynamically create and manage SQL-like tables, data, and relationships in a MongoDB-based system?
I'm building a web application where users can execute SQL queries on predefined tables for an exam module. The backend is in Django, and the database is MongoDB. I want to allow admins to dynamically: Create table schemas (table name, columns, data types, primary keys). Insert data into these tables. Define relationships between tables (e.g., foreign keys). Validate and execute SQL queries submitted by users based on the stored table schemas and relationships. The goal is to minimize backend involvement by providing a user-friendly admin interface for managing tables and relationships. I am looking for best practices or suggestions on: Efficiently storing table schemas and relationships in MongoDB. Dynamically executing and validating SQL-like queries based on these schemas. Simplifying the admin interface for managing tables and relationships in the frontend. Any advice, code snippets, or recommended libraries/tools would be appreciated. -
Gmail with Oauth rejects my token/password
I am trying to send mail from Django. I've tried two different ways, both of which fail in different ways. When I tried using an app password, I had no errors, but the email just never arrived. And the sender's outbox is empty, too. But that was after I tried the modern method, OAuth. After a process that I would never have finished without ChatGPT (because nobody else has created a guide that I can find), I set up something that almost works. I have a file with a refresh token in it, and a custom backend that uses it. But when it's time to send an email, I'm told "Username and Password not accepted." Here's what the token file is like: { "token": "[secret]", "refresh_token": "[secret]", "token_uri": "https://oauth2.googleapis.com/token", "client_id": "[secret]", "client_secret": "[secret]", "scopes": ["https://www.googleapis.com/auth/gmail.send"], "universe_domain": "googleapis.com", "account": "", "expiry": "2025-01-05T07:39:06.980351Z" } And this is the backend: from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from django.core.mail.backends.smtp import EmailBackend from pathlib import Path import os class GmailOAuth2Backend(EmailBackend): def _get_access_token(self): dir = Path(__file__).resolve().parent file = os.path.join(dir, 'oauth2tokenfile.secret.json') creds = Credentials.from_authorized_user_file(file) if creds.expired and creds.refresh_token: creds.refresh(Request()) return creds.token def open(self): self.password = self._get_access_token() super().open() And finally, my settings EMAIL_BACKEND = "[secret].GmailOAuth2Backend" EMAIL_HOST … -
how to create a virtual try on website using django
I encountered a CUDA (NVIDIA) version error while attempting to set up a virtual try-on website for e-commerce. I tried several Python versions, but CUDA is not compatible with Django. If I downgrade to resolve the CUDA issue, other packages become incompatible. I need the full source code and an explanation for implementing a virtual try-on e-commerce website. -
page not found error when using python social auth login for okta
I am getting a "Backend not found" error when trying to setup okta oidc login using social-auth-app-django 5.4.2 here are the settings: 'social_django' is added to INSTALLED_APPS 'social_django.middleware.SocialAuthExceptionMiddleware' is added to MIDDLEWARE "social_django.context_processors.backends" and "social_django.context_processors.login_redirect" are added to the list in TEMPLATES['OPTIONS']['context_processors'] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.okta_openidconnect.OktaOpenIdConnect', ] LOGIN_URL = 'auth/login/okta_openidconnect/' and in the list of project urls, this is added path('auth/', include('social_django.urls', namespace='social')) when i go to the login url, I get a 404 page not found error Backend not found Request Method: GET Request URL: https://my.site/auth/login/okta_openidconnect/?next=/en-us/ Raised by: social_django.views.auth Using the URLconf defined in xxx.urls, Django tried these URL patterns, in this order: ... 17. en-us/ auth/ login/<str:backend>/ [name='begin'] The current path, en-us/auth/login/okta_openidconnect/, matched the last one. there are other settings, like SOCIAL_AUTH_OKTA_OPENIDCONNECT_KEY and the SOCIAL_AUTH_PIPELINE, which i'm sure are correct and i believe that even if they were not correct, it's unrelated to not having the proper backend. so does anyone see a mistake in this setup that could be causing the backend fail? -
playwright with django: 502 Bad Gateway Error
My webapp doesn't work for any portion that uses playwright. Everything works in localhost (including playwright). When trying to view the home page (no playwright), it works 100%. When trying to use code from the library playwright, it gives me a: 502 Bad Gateway nginx/1.18.0 (Ubuntu) What can I do to troubleshoot this? I tried disabling firewall, but that didn't make difference. I tried debugging by throwing an exception for each line of code. Sometimes it moves a few lines further and other times it doesn't move a few lines further. Again, only code that uses playwright will give me this error. I'm using Django 5.1.4. Playwright is latest version. Here's some code from playwright: try: await page.goto('https://pantry.plentifulapp.com/login') await expect(page.get_by_test_id("LoginForm-44")).to_be_visible(timeout=3000) except: content = "Plentiful is down." return content #Find email input and type it. await page.get_by_test_id("LoginForm-47").click() await page.keyboard.type(username) #find password input, type it, and then press enter. await page.get_by_test_id("LoginForm-53").click() await page.keyboard.type(password) await page.keyboard.press("Enter") -
502 Bad Gateway Elastic Beanstalk, No Module named "ebdjango"
I'm trying to deploy a django application using elastic beanstalk, I've followed all the steps from the AWS documentation and I get a 502 bad gateway error. I looked through the elastic beanstalk logs like similar questions suggested and the same error keeps appearing that I didn't see in any other posts. Jan 6 20:42:24 ip-172-31-32-9 web: ModuleNotFoundError: No module named 'ebdjango' I can only find similar questions about django module not ebdjango, and pip install obviously doesn't work. I've included other file info that might be relevant. If anything else is needed I'm happy to provide it. django.config file option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application aws:autoscaling:launchconfiguration: DisableIMDSv1: true' config.yml branch-defaults: default: environment: django-env-2 group_suffix: null environment-defaults: django-env: branch: null repository: null global: application_name: django-env-2 branch: null default_ec2_keyname: null default_platform: Python 3.8 default_region: eu-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application EB Error Logs Jan 6 20:42:25 ip-172-31-32-9 web: Traceback (most recent call last): Jan 6 20:42:25 ip-172-31-32-9 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/gunicorn/arbiter.py", line 608, in spawn_worker Jan 6 20:42:25 ip-172-31-32-9 web: worker.init_process() Jan 6 20:42:25 ip-172-31-32-9 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/gunicorn/workers/gthread.py", line 94, in init_process Jan 6 20:42:25 ip-172-31-32-9 web: super().init_process() Jan 6 20:42:25 ip-172-31-32-9 web: … -
Need help fixing a Django 404 error, not finding a static page using URLConf
My Django project is a single-application website where the homepage shows articles/posts from my database, and will have pages for tag topics and year/month archives. All other pages are static pages for photo and video galleries, and an about page — they don't use the database at all. I'm trying to get one of the static pages to display, but I keep running into a 404 error with the following (note: I replaced the application's name with "<app_name>"): No article found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/illustrations Raised by: <app_name>.views.ArticleDetailView Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: admin [name='home'] <slug:slug> [name='article_detail'] The current path, illustrations, matched the last one. The homepage shows all articles in ListView, and you can click individual articles to view them in DetailView with the designated slug as the URL. The "illustrations" file is a separate static HTML page I'll use that has nothing to do with the database or either of the List or Detail views. I can't tell if I should make the homepage a separate app, or if I just need to change my URLs/Views files. (I'm learning Django and Python, so I'm … -
What is the most secured approach to prevent html video download from a django website
I have a website that i want to do the following: prevent users from downloading the videos. I need the best practice ensure that my videos can only be played within the website and no where else I tried to disguise the video source link to blob url object but it's downloadable. Even when I copy the blob url object in to browser the video still plays, that another thing i need to prevent. PLEASE HELP! -
How to run a Redis listener in Django when the server starts?
I'm working with Django and I have a Redis listener that I run with the following custom command: import os import asyncio from django.core.management.base import BaseCommand from notifications.core.redis_listener import RedisListener class Command(BaseCommand): help = 'Listen for notifications with metadata from Redis in real-time' def handle(self, *args, **kwargs): redis_host = os.getenv('REDIS_HOST') redis_port = int(os.getenv('REDIS_PORT')) redis_password = os.getenv('REDIS_PASSWORD') redis_channel = 'notifications_channel' # Redis channel to subscribe to ssl = os.getenv('REDIS_SSL', 'False') == 'True' # Conditionally Use "ssl_cert_reqs" if ssl: redis_listener = RedisListener( redis_host=redis_host, redis_port=redis_port, redis_password=redis_password, redis_channel=redis_channel, ssl=ssl, ssl_cert_reqs='none' ) else: redis_listener = RedisListener( redis_host=redis_host, redis_port=redis_port, redis_password=redis_password, redis_channel=redis_channel, ssl=ssl, ssl_cert_reqs='none' ) # Run the listener function with asyncio loop = asyncio.get_event_loop() loop.run_until_complete(redis_listener.listen_to_redis()) Currently, I start the Redis listener by running: python manage.py listen_redis However, I want the Redis listener to start automatically when I run the Django development server with: python manage.py runserver I would like this Redis listener to run concurrently with the Django development server without needing to manually start it via a custom management command. How can I achieve this? In my apps.py I tried this - from django.apps import AppConfig import os import threading import asyncio from notifications.core.redis_listener import RedisListener from django.db.backends.signals import connection_created from django.db import connections class …