Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
after using login(request) to create a session in my login view, the session is lost when i access another view in Django
I'm trying to create an API client server model in Django, but every time i log into a user in my login view. When i need to use the information and session from the login, for some reason it gets reset to AnonymousUser in my stories view. And if i use @login required it just redirects me to the login page as if i didn't just authorize and create a session with the user moments ago. Here is my views.py: @csrf_exempt def login_view(request): if request.method == 'POST': payload = request.POST # Validate payload keys if 'Username' not in payload or 'Password' not in payload: return JsonResponse({'message': 'Username or password missing'}, status=400) username = payload['Username'] password = payload['Password'] user = authenticate(request, username=username, password=password) if user is not None: # Log the user in and store session data login(request, user) return JsonResponse({'message': 'Login successful', 'user_id':user.id}, status=200) else: # Incorrect username or password return JsonResponse({'message': 'Incorrect username or password'}, status=401) @csrf_exempt @login_required def stories(request): if request.method == 'POST': if request.user.is_authenticated: print(request.user.username) # Retrieve data from the POST request headline = request.POST.get('Headline') category = request.POST.get('Category') region = request.POST.get('Region') details = request.POST.get('Details') # Get the current user's author object author = Author.objects.get(user=request.user.id) author_name = author.name … -
Getting Forbidden You don't have permission to access this resource error while depolye django project with apache and mod_wsgi
Here is my error from error_log [Fri Mar 22 16:00:09.035343 2024] [wsgi:info] [pid 63294:tid 63294] mod_wsgi (pid=63896): Process 'swpdoc' has died, deregister and restart it. [Fri Mar 22 16:00:09.035428 2024] [wsgi:info] [pid 63294:tid 63294] mod_wsgi (pid=63896): Process 'swpdoc' terminated by signal 1 [Fri Mar 22 16:00:09.035443 2024] [wsgi:info] [pid 63294:tid 63294] mod_wsgi (pid=63896): Process 'swpdoc' has been deregistered and will no longer be monitored. [Fri Mar 22 16:00:09.036602 2024] [wsgi:info] [pid 63897:tid 63897] mod_wsgi (pid=63897): Starting process 'swpdoc' with uid=48, gid=48 and threads=15. [Fri Mar 22 16:00:09.039512 2024] [wsgi:info] [pid 63897:tid 63897] mod_wsgi (pid=63897): Python home /opt/Production/swpdoc/venv311. [Fri Mar 22 16:00:09.039593 2024] [wsgi:info] [pid 63897:tid 63897] mod_wsgi (pid=63897): Initializing Python. Python path configuration: `` ` ``` `PYTHONHOME = '/opt/Production/swpdoc/venv311' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir = '/opt/Production/swpdoc/venv311/lib64/python3.11' sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/opt/Production/swpdoc/venv311' sys.base_exec_prefix = '/opt/Production/swpdoc/venv311' sys.platlibdir = 'lib64' sys.executable = '/usr/bin/python3' sys.prefix = '/opt/Production/swpdoc/venv311' sys.exec_prefix = '/opt/Production/swpdoc/venv311' sys.path = [ '/opt/Production/swpdoc/venv311/lib64/python311.zip', '/opt/Production/swpdoc/venv311/lib64/python3.11', '/opt/Production/swpdoc/venv311/lib64/python3.11/lib-dynload', ]``` Here is my httpd.conf ` WSGIScriptAlias / /opt/Production/swpdoc/techdocsweb/swpdoc/wsgi.py WSGIApplicationGroup %{GLOBAL} <Directory /opt/Production/swpdoc/techdocsweb/swpdoc> <Files wsgi.py> Require all granted </Files> … -
Python 3.12 pip install mod_wsgi fails
I am trying to deploy Django rest framework on my Debian 10 server. I am using Apache2 but he keeps crashing because its not using the right python version. I am using python3.12 version for my project : python --version Python 3.12.2 But Apache2 is running with python3.7 so its crashing because it cant find Django Module Apache/2.4.38 (Debian) mod_wsgi/4.6.5 Python/3.7 configured I tried to install mod_wsgi with pip but I keep getting this error : /usr/bin/ld: final link failed: nonrepresentable section on output collect2: error: ld returned 1 exit status error: command '/usr/bin/gcc' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mod_wsgi Failed to build mod_wsgi ERROR: Could not build wheels for mod_wsgi, which is required to install pyproject.toml-based projects Thanks to everyone fo your time ! I tried everything I found on existing topics. I am expecting a solution to be able to install mod_wsgi and use the right python version on my apache2 server -
cimpl.KafkaException: KafkaError{code=_INVALID_ARG,val=-186,str="Failed to create consumer: sasl.username and sasl.password must be set"}
I'm trying to build this Microservices project But get this error on consumer.py and also vsc says its unable to import confluent_ Here´s the code for consumer.py: import os import json import django from confluent_kafka import Consumer from rest_framework.exceptions import ValidationError os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") django.setup() consumer = Consumer({ 'bootstrap.servers': os.environ.get('KAFKA_BOOTSTRAP_SERVER'), 'security.protocol': os.environ.get('KAFKA_SECURITY_PROTOCOL'), 'sasl.mechanism': 'PLAIN', 'sasl.username': os.environ.get('KAFKA_USERNAME'), 'sasl.password': os.environ.get('KAFKA_PASSWORD'), 'group.id': os.environ.get('KAFKA_GROUP'), 'auto.offset.reset': 'earliest' }) consumer.subscribe([os.environ.get('KAFKA_TOPIC')]) while True: msg = consumer.poll(1.0) if msg is None: continue if msg.error(): print(f"Consumer error: {msg.error()}") continue if msg is not None and not msg.error(): topic = msg.topic() value = msg.value() data = json.loads(value) print(f'Got this message with Topic: {topic} and value: {value}, with Data: {data}') if topic == os.environ.get('KAFKA_TOPIC'): if msg.key() == b'create_user': try: print(f"Order created successfully for user {data['userID']}") except ValidationError as e: print(f"Failed to create order for user {data['userID']}: {str(e)}") consumer.close() Here's producer.py: from confluent_kafka import Producer import os producer= Producer({ 'bootstrap.servers':os.environ.get('KAFKA_BOOTSTRAP_SERVER'), 'security.protocol':'SASL_SSL', 'sasl.mechanism': 'PLAIN', 'sasl.username':os.environ.get('KAFKA_USERNAME'), 'sasl.password':os.environ.get('KAFKA_PASSWORD'), }) I have tried downgrading my Python image from 3.12 to 3.10 but still doesnt work tried changing this FROM python:3.10 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app/ CMD python manage.py runserver 0.0.0.0:8000 -
Why do I receive 403 error while sending a post request using axios in my react file? And how should I code a sign up page from scratch?
I'm trying to code a sign up page in my django project. I have two apps named "api" and "frontend". I really am not sure if I'm doing it correctly but my main idea is to have a registeration form in http://127.0.0.1:8000/sign-up so that when the user presses the submit button, it would send a post request and my CreateUserView class in api/views.py would get that and the new user would be registered. frontend/urls.py: from django.urls import path from .views import index from api.views import RegisterView urlpatterns = [ path('sign-up', index), path('register', RegisterView.main), ] frontend/views.py: from django.shortcuts import render def index(request, *args, **kwargs): return render(request, 'frontend/index.html') frontend/src/components/App.js: import SignUp from "./SignUp"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import { render } from "react-dom"; function App() { return ( <div> <BrowserRouter> <Routes> <Route path="/sign-up" element={<SignUp />} /> </Routes> </BrowserRouter> </div> ); } export default App; const appDiv = document.getElementById("app"); render(<App />, appDiv); frontend/src/components/SignUp.js: import React, { Component, Fragment, useState } from "react"; import axios from "axios"; function SignUp() { const [gmailAdress, setGmailAdress] = useState(""); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); return( <Fragment> <div> <button onClick={() => axios.post("/sign-up", { method: "POST", headers: { "Content-Type": "application/json" }, … -
Is there a way to optimize Large data set to load fast in Django
I have a model with over 6 millions object and anytime I am accessing the object page in my admin page its load very slow it even runs to time out sometimes and also the same thing to my view so I would like to get help if there is any recommendations method I can use for the issue. The project is hosted in AWS elastic beanstalk. The database configuration is attached to the Post Thanks in advance 🙂 Database configuration The database object I have increased the database resources but still the same. From db.t2.medium To db.t3.medium -
Swagger/drf_yasg: either schema or type are required for Parameter object (not both)
I have the following path: path('path/<int:object_id>', function, name='function'), The way it is, drf_yasg is generating the documentation for object_id as if it as a string: So I decided to manually input the information in the swagger_auto_schema decorator: @swagger_auto_schema( method='PATCH', manual_parameters=[ openapi.Parameter('object_id', openapi.IN_PATH, required=True, description='Object ID'), # query parameters ], # operation_description, responses, etc ) @api_view(['PATCH']) @permission_classes([IsAuthenticated]) def function(request, object_id) However, by doing this, drf_yasg raises the error either schema or type are required for Parameter object (not both)!, and I can't fix this unless I remove the object_id path parameter form the decorator Anyway, I'm interested in being able to explicitly descibe my path parameter in the decorator instead of letting drf_yasg doing this by myself How can I fix this? -
Getting error django with rabbitmq ImproperlyConfigured: Requested setting REST_FRAMEWORK
Hi Guys I'm newbie in django i try to integrate microservices django with rabbitmq but i got the error like this django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. can someone help me this is for my file manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys from MicroserviceImage.listenerRabbitMq import Command import threading def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MicroserviceImage.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) def start_consuming(service_name): Command().handle() if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MicroserviceImage.settings') # Start the consumer threads consumer_threads = [] for i in range(1): thread = threading.Thread(target=start_consuming, args=('crawler{}-service'.format(i),)) consumer_threads.append(thread) # Start all the threads for thread in consumer_threads: thread.start() # Run the Django management command main() and this is for setting.py """ Django settings for MicroserviceImage project. Generated by 'django-admin startproject' using Django 4.1.13. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ … -
Trying to consume API data from Django backend to React
I am trying to consume the Bing web search api. I have my view setup in Django backend. I was able to retrieve the search result data in terminal. But I am getting an error when fetching the data in React. If you could please help with a detailed response it would be much appreciated! Thanks in advance. Django runserver terminal when refreshing React page: 'name': 'iPhone 13 review | Tom&#39;s Guide', 'noCache': False, 'primaryImageOfPage': {'height': 80, 'imageId': 'OIP.63KzaXCF-d8nPkQdmM6bWgHaDL', 'thumbnailUrl': 'https://www.bing.com/th?id=OIP.63KzaXCF-d8nPkQdmM6bWgHaDL&w=80&h=80&c=1&pid=5.1', 'width': 80}, 'snippet': 'The<b> iPhone 13</b> is a great ' 'budget-friendly flagship phone with a ' 'brighter display, longer battery life and ' 'powerful cameras. Read our in-depth ' 'review to find out its strengths and ' 'weaknesses, and how it compares to the ' 'iPhone 14 and other models.', 'thumbnailUrl': 'https://www.bing.com/th?id=OIP.63KzaXCF-d8nPkQdmM6bWgHaDL&w=80&h=80&c=1&pid=5.1', 'url': 'https://www.tomsguide.com/reviews/iphone-13'}], 'webSearchUrl': 'https://www.bing.com/search?q=iphone+13'}} Internal Server Error: /home/ Traceback (most recent call last): File "C:\Users\storm\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\storm\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "C:\Users\storm\AppData\Local\Programs\Python\Python310\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'list' object has no attribute 'get' [22/Mar/2024 14:15:37] "GET /home/ HTTP/1.1" 500 72597 SearchResults.js React file: import React, { useState, useEffect } from … -
Favicon Not loading in Django development as well as production
I have already tried all the solutions available as u can see in the code but No help. I can browse the favicon in my browser but not on webpage favicon U can see the no. of attempts base.html <link rel="shortcut icon" type="image/png" href="iitiansedu/static/image/favicon.png"> <link rel="shortcut icon" href="{% static 'iitiansedu/static/images/favicon.ico' %}"/> <link rel="icon" href="{% static 'iitiansedu/images/favicon.png' %}" type="image/x-icon"> <link rel="icon" href="{% static 'iitiansedu/images/favicon.ico' %}"> <link rel="icon" href="{% static 'images/favicon.png' %}"> <link rel="apple-touch-icon" sizes="180x180" href="{% static 'images/apple-touch-icon.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'images/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'images/favicon-16x16.png' %}"> <link rel="manifest" href="{% static 'images/site.webmanifest' %}"> <link rel="mask-icon" href="{% static 'images/safari-pinned-tab.svg' %}" color="#5bbad5"> url.py from django.contrib import admin from django.urls import path, include from . import views from django.conf import settings from .views import SearchView from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import include, path from django.views.generic.base import RedirectView from .views import * from django.templatetags.static import static from django.conf import settings from django.conf.urls.static import static from django.urls import path from django.contrib import admin from carousel import views as carousel_views favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True) urlpatterns = [ path('admin/', admin.site.urls), path('', views.HomePage.as_view(), name='home'), # path('favicon.ico', RedirectView.as_view(url='static/favicon.ico')), path('favicon.ico', RedirectView.as_view(url=static('favicon.ico'))), /etc/nginx/sites-enabled location = /favicon.ico { access_log off; log_not_found off; } location /static/ … -
Problems deploying Wagtail 6
I'm upgrading from Wagtail 4.2.4 to 6.0.1 and I made a lot of changes taking into consideration all the deprecated libraries. Everything works localy but when I try to deploy to my development site the GitHub Action runner fails with the following Error: remote: ModuleNotFoundError: No module named 'wagtail.contrib.modeladmin' remote: ! Error while running '$ python manage.py collectstatic --noinput'. I checked and the wagtail-robots library still uses the deprecated contrib.modeladmin. Any ideas? -
AUTH_USER_MODEL refers to model 'Socialmedia.User' that has not been installed
I created my custom user model and I have a function which allows users to sign in . I think my custom user model is incompatible with my function because it wouldn't allow me to do User.objects.get(username=username) . How can I fix this so I can use the db? AUTH_USER_MODEL refers to model 'Socialmedia.User' that has not been installed my views.py: def sign_up(request): if request.method == 'POST': username = request.POST.get("username").lower() password = request.POST.get("password") email = request.POST.get("email") password2 = request.POST.get("password2") users = User.objects.get(username=username) if users is not None: messages.error("The user already exists, please select a different username") else: user = User.objects.create_user(username=username, password=password, email=email) user.save() return render(request, 'usermgm/costume_register.html') models.py: in models i created imports: from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser, BaseUserManager models.py: class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True') return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_active = models.BooleanField(default=True) is_staff = … -
Change Windows Logon
I was researching how I could change Windows credentials to personalized ones, I saw that in old versions of Windows they used Gina, but now with Windows 10 we have to use the Credential providers, and I'm not a good understander of Windows, but the company where I'm interning told me to create a Windows login with facial recognition, can you tell me if this is possible and if it's possible what to use? Thank you very much I already have a project in Django with facial recognition for web attendance with anti-spoofing with connection to the Postgre database, I don't know if I can, for example, use a web view I already tried to create something with Gina, but I didn't get the expected result. -
django ActiveSession MultipleObjectsReturned
Every now and then I get complaints from users that they are unable to login. I see the following exception in debug.log. The database table authentication_activeSession has two entries for the user's session. The offending line of code is session = ActiveSession.objects.get(user=user) How should this be countered? File "/home/admin/site/django-api/api/submissions/viewsets/sitesubmissions.py", line 19, in create session = ActiveSession.objects.get(user=user) File "/home/siteadmin/.local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/siteadmin/.local/lib/python3.9/site-packages/django/db/models/query.py", line 439, in get raise self.model.MultipleObjectsReturned( api.authentication.models.active_session.ActiveSession.MultipleObjectsReturned: get() returned more than one ActiveSession -- it returned 2! -
Django: "Cannot assign must be a "X" instance", don't want to fetch the object
I have the following view on my Django app and I need to update one object status_id is a ForeignKey field and it has some default values loaded via fixtures def stopObject(request, id_object): object = Object.objects.get(id=id_object) object.status_id = 1 object.save() I'm getting the classical error where I need to assign the object, not its Id. There are countless questions on SO about this problem, but I came looking for an answer I didn't found I know very well I can just perform a fetch from the database and assign to status, but I want to explore other possibilities, even though they may not be the best practices -
Django or FastAPI for an E-commerce website?
I'm planning to build an e-commerce website and I'm torn between choosing FastAPI or Django for the backend. Considering factors like scalability, security, and ease of development, which framework would be better suited for an e-commerce site? Old Django or newer FastAPI I'd appreciate insights or experiences from the community to help make an informed decision. -
Upgraded to Django 4.2, import storages module failed
I recently upgraded Django 4.2 and was applying storage change to my project. Ran into an import error with the storage module. screenshot for my code and the error I double checked the package versions. I tried to re-install the requirements. Both pycharm and mypy threw me the error. I tried to import that module in shell and it worked fine. Does anyone know why this is happening? -
ValidationError doesn't show up in my registration form(Django)
i wrote 2 validation functions in my forms.py but they don't show up in my registration form when i fill fields with wrong data views.py: def register(request): form=RegisterUserForm() if request.method== 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): user=form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save() return render(request, 'user/register_done.html') else: form = RegisterUserForm() return render(request, 'user/register.html',{'form': form} ) forms.py class RegisterUserForm(forms.ModelForm): username = forms.CharField(label='Логин') password = forms.CharField(label='Пароль', widget=forms.PasswordInput()) password2 = forms.CharField(label='Повтор пароля', widget=forms.PasswordInput()) class Meta: model=get_user_model() fields=['username','email','first_name','last_name','password','password2'] labels={ 'email':'E-mail', 'first_name':'Имя', 'last_name':'Фамилия', } def cleaned_password2(self): cd=self.cleaned_data if cd['password']!=cd['password2']: raise forms.ValidationError('Пароли не совпадают!') return cd['password'] def clean_email(self): email = self.cleaned_data['email'] if get_user_model().objects.filter(email=email).exists(): raise forms.ValidationError('Такой адрес уже есть') return email HTML template {% extends 'movieapp/base.html' %} {% block content %} <h1>Регистрация</h1> <form method='post'> {% csrf_token %} {{ form.as_p }} <p><button type="submit">Регистрация</button></p> </form> {% endblock %} urls.py from django.contrib.auth.views import LogoutView from . import views from django.urls import path urlpatterns = [ path('login/',views.LoginUser.as_view(), name='login'), path('logout/',LogoutView.as_view(), name='logout'), path('register/',views.register,name='register') ] I am only learning django and still don't understand why validationerror doesn't show up and return me on the same page when i write wrong password on passwordcheck and the already existing email adress -
Application error after deployed my django project in Heroku
Trying to launch a Django web app on Heroku. Get Application Error: An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details. heroku logs: PS C:\django24_project\student_info_project> heroku logs --tail 2024-03-22T14:45:16.638981+00:00 app[web.1]: File "", line 488, in _call_with_frames_removed 2024-03-22T14:45:16.638981+00:00 app[web.1]: File "", line 1387, in _gcd_import 2024-03-22T14:45:16.638982+00:00 app[web.1]: File "", line 1360, in _find_and_load 2024-03-22T14:45:16.638982+00:00 app[web.1]: File "", line 1324, in _find_and_load_unlocked 2024-03-22T14:45:16.638982+00:00 app[web.1]: ModuleNotFoundError: No module named 'mysite' 2024-03-22T14:45:16.639044+00:00 app[web.1]: [2024-03-22 14:45:16 +0000] [9] [INFO] Worker exiting (pid: 9) 2024-03-22T14:45:16.644266+00:00 app[web.1]: [2024-03-22 14:45:16 +0000] [10] [INFO] Booting worker with pid: 10 2024-03-22T14:45:16.647216+00:00 app[web.1]: [2024-03-22 14:45:16 +0000] [10] [ERROR] Exception in worker process 2024-03-22T14:45:16.647217+00:00 app[web.1]: Traceback (most recent call last): 2024-03-22T14:45:16.647218+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker 2024-03-22T14:45:16.647219+00:00 app[web.1]: worker.init_process() 2024-03-22T14:45:16.647219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/workers/base.py", line 134, in init_process 2024-03-22T14:45:16.647219+00:00 app[web.1]: self.load_wsgi() 2024-03-22T14:45:16.647219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2024-03-22T14:45:16.647220+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2024-03-22T14:45:16.647220+00:00 app[web.1]: ^^^^^^^^^^^^^^^ 2024-03-22T14:45:16.647220+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/app/base.py", line 67, in wsgi 2024-03-22T14:45:16.647220+00:00 app[web.1]: self.callable = self.load() 2024-03-22T14:45:16.647221+00:00 app[web.1]: ^^^^^^^^^^^ 2024-03-22T14:45:16.647221+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2024-03-22T14:45:16.647221+00:00 app[web.1]: return self.load_wsgiapp() 2024-03-22T14:45:16.647221+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^ 2024-03-22T14:45:16.647221+00:00 … -
How to dynamically change resource class in Django Import-Export admin based on user group?
I am using Django Import-Export library to manage export functionalities in my Django admin interface. I have a requirement where I need to dynamically change the resource class based on the user's group membership. Here's a simplified version of what I am trying to achieve: from import_export.admin import ImportExportModelAdmin from django.contrib import admin from .resources import RawFileDMDResource, RawFileResource class RawFileAdmin(ImportExportModelAdmin): resource_class = RawFileResource [...] def get_resource_class(self, request=None): resource_class = self.resource_class if request is None: user = get_user() else: user = request.user if user.groups.filter(name='DMD ext_users').exists(): resource_class = RawFileDMDResource return resource_class However, the get_resource_class method expects a request argument. It seems that the Import-Export library doesn't provide the request object in the context of this method. Is there a way to access the current user's information or request object within the get_resource_class method without explicitly passing the request object? -
is this a right way to use regular exprissio?
how to use regular expression with python? i searched and write code in my laptop i get the output as i want but on the web site it didn't match in Courser a course python for everybody i tried to solve an assignment but it didn't work on the web site but it worked correctly on my own laptop it's about regular expression. import re fh = open("regex_sum_42.txt") text = fh.read() number_final = re.findall('[0-9]+',text) total = 0 for i in number_final: i = int(i) total = total + i; print(total) print(number_final) fh.close() -
setting async python-telegram-bot(ptb) webhooks using django
setting async python-telegram-bot(ptb) webhooks using django I am using Django==5.0.3 and python-telegram-bot==21.0.1 I have developed several telegram bots using fastapi+uvicorn and ptb but I can't make django work with python telegram bot library. I get timeout error when I include this line: async with application: I am using postman to simulate a telegram request with a post request with a body like this: {"update_id": 400838435, "message": {"message_id": 627, "from": {"id": 357686176, "is_bot": false, "first_name": "-----", "last_name": "---", "username": "----", "language_code": "en"}, "chat": {"id": 357686176, "first_name": "----", "last_name": "------", "username": "----", "type": "private"}, "date": 1711115302, "text": "hi"}} here is my code. I have tested both uvicorn nameoftheproject.asgi:application and python manage.py runserver to run the project but the result is the same from django.shortcuts import render, HttpResponse from django.http import HttpRequest from django.views.decorators.csrf import csrf_exempt from . import botInstance # from handlers.handler_mapping import set_handlers from .handlers.handler_mapping import set_handlers from telegram.ext import MessageHandler, filters, ContextTypes from telegram import Update import json # Create your views here. async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE): await Update.message.reply_text(update.message.text) @csrf_exempt async def say_hello(request: HttpRequest): #print(request) # print(request.body) #print(request.GET) token = "-------A" application = botInstance.get(token) if request.method == 'POST': print(json.loads(request.body)) async with application: pass # await application.start() # # … -
VERCEL Deployment : NotSupportedError at / deterministic=True requires SQLite 3.8.3 or higher
How do i solve this? i visited the sqlite website but is shows only version 3.45.2 version available to download whereas when hosting the website it says version 3.8.3 or higher is required? How do i update my dbsqlite version ? anyone please help and also english is not my first language so please do not use any fancy words I tried to download from the db sqlite but it doesnt show version 3.8.3 so i didnt download it thinking it might cause errors adn also stack over flow what is your problem just let me post this -
Readonly map for GeoDjango fields in Django>=4.0?
I was searching old answers on how to show the dynamic Openlayers map but not allow you to move/change the coordinates/geometry of a given GeoDjango field (a PointField in my case) in the Django Admin. Old solutions mention using the OSMGeoAdmin class (from django.contrib.gis.admin), which allows you to set the modifiable attribute to False to make the map be shown but not modifiable. This is exactly what I want. However, that class is deprecated since Django 4.0, and you are now prompted to use ModelAdmin or GISModelAdmin instead, but none of the two allow me to replicate the same behaviour as OSMGeoAdmin. I searched the documentation for GISModelAdmin and it points that I can send some parameters to the gis_widget using the dictionary gis_widget_kwargs, but the modifiable attribute is still not working, so I am beggining to think that the functionality was removed. Example of code to pass parameters to the gis_widget: @admin.register(m.City) class CityAdmin(GISModelAdmin): gis_widget_kwargs = {'attrs':{'map_width':1200, 'modifiable':False}} Am I missing something? Is that really no longer possible with GISModelAdmin? Do I have to go through the annoying process of creating my own widget to replicate this behaviour? If someone has faced the same situation, did you manage to … -
Background video scaling through the whole page
right now the video is scaling through the whole page, like when I start scrolling it is not fixed on the first page but scales downwards too. I want it to be fixed at the first page of home screen, for example at 1920*1080 resolution for computer users HTML : <div class="home-video"> <video autoplay muted loop id="bg-video"> <source src="{% static 'core/background/background-video.mp4' %}" type="video/mp4"> </video> </div> CSS : .home-video { position: fixed; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; z-index: -1; } #bg-video { width: auto; height: auto; min-width: 100%; min-height: 100%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: -1; } Tell me what I'm doing wrong