Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
stuck with multithreading
i am reading multiple hdf5 files and those hdf5 file will be having datasets in heirarchy , i am fetching data from these hdf5 files , i am using multi threading inside hdf5 file to increase reading speed, also tell how can i make this fast, do i need to change my structure or reading way, i amm using python 2.7 and django 1.8: present is : their are multiple client_id.hdf5 , inside it multiple ship_ids -> report_types-> time_stamp-> in that data for that time i did this , it is only printing till Data fetched. Starting multiprocessing... ('Processing client:', 112): import h5py import os import json import time from datetime import datetime from multiprocessing import Pool from vast import models import dateutil.parser from_date = dateutil.parser.parse('2023-06-01') to_date = dateutil.parser.parse('2024-04-30') boss_dir = '/home/bwit-laptop3/boss' new_structure_dir = os.path.join(boss_dir, 'Data/new_mirror_data_for_fetching') def fetch_and_save_data(): data_dict = {} mirrors_info = models.mirrorv2_info.objects.filter(report_date__gte=from_date, report_date__lt=to_date, client_id=112) for mirror_info in mirrors_info: ship_id = mirror_info.ship_id report_date = mirror_info.report_date client_id = mirror_info.client_id report_type = mirror_info.report_type client_dict = data_dict.setdefault(client_id, {}) ship_dict = client_dict.setdefault(ship_id, {}) report_type_dict = ship_dict.setdefault(report_type, {}) date_string = report_date.strftime("%Y-%m-%d %H:%M:%S") report_date_list = report_type_dict.setdefault(date_string, []) print("Data fetched. Starting multiprocessing...") get_data_multiprocess(data_dict) file_path = os.path.join(boss_dir, 'data_fetch_new_way.json') directory = os.path.dirname(file_path) if not os.path.exists(directory): os.makedirs(directory) with open(file_path, … -
django.db.utils.OperationalError: could not translate host name "postgres.railway.internal"
django.db.utils.OperationalError: could not translate host name "postgres.railway.internal" to address: nodename nor servname provided, or not known my django project was working great, until a changed the setting.py file to deploy it in railway, using the variables railway provides. since then i can't runserv or migrate, that i get this error... here is the database settings a changed to use the railway variables DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'railway', 'USER': 'postgres', 'PASSWORD': DB_PASSWORD_RAIL, 'HOST': 'postgres.railway.internal', 'PORT': '5432', } } error when i runserver or migrate django.db.utils.OperationalError: could not translate host name "postgres.railway.internal" to address: nodename nor servname provided, or not known -
Why celery beat scheduler still running after expires in django celery
PeriodicTask.objects.create( interval=interval, crontab=crontab, clocked=clocked, name=data["name"], task=data["task"], # dropdown args=json.dumps(json.loads(data["args"])), one_off=True if schedule_type == "clocked" else False, expires=datetime.strptime(data["expires"], '%Y-%m-%d %H:%M:%S.%f') if data["expires"] else None ) -its still running after set expires time -its not calling function but its hit worker ex: in worker terminal [2024-07-22 07:06:16,334: INFO/MainProcess] Task test[390404a1-9814-4208-85a2-6e1269bc09d9] received [2024-07-22 07:06:16,334: INFO/MainProcess] Discarding revoked task: test[390404a1-9814-4208-85a2-6e1269bc09d9] and in celery beat terminal [2024-07-22 07:06:16,327: WARNING/MainProcess] 390404a1-9814-4208-85a2-6e1269bc09d9 has an expiration date in the past (16.325898s ago). We assume this is intended and so we have set the expiration date to 0 instead. According to RabbitMQ's documentation: "Setting the TTL to 0 causes messages to be expired upon reaching a queue unless they can be delivered to a consumer immediately." If this was unintended, please check the code which published this task.``` -
Python (Django) Data Manipulation
"How can I transform Excel attendance data into a specific database insertion format?" **I have data in Excel that looks like this: ** This is data format I **need to convert this into a format suitable for database insertion, like this: ** Data That i want -
Uploaded media doesn't server in production mode without restarting django
I need to serve media in Django in production mode and it is very little need to serve telegram user photos in Django admin. so I know everything about Django it's not for serving files or media so there is no need to repeat repetitive things. I just need to serve media in production mode for my purpose so I use WhiteNoise to do this and append this lines: MIDDLEWARE = [ ... 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'medias') in urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('botAPI.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS[0]) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) else: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in wsgi.py I put this: ... application = get_wsgi_application() application = WhiteNoise(application, root=MEDIA_ROOT, prefix='/media/') .... It works correctly and serves media files in production mode. but for new media for example uploading an image in Django admin I have to restart Django to access that media. is there any way to solve this problem or another way in Django to serve … -
Use correct Bootstrap CSS in Django forms for Radio select form input
How to get Django forms to render correct Bootstrap to a Radio select form input? I passed form-control form-check classess in the form, yet the form HTML produced is not accurate for radio select option. I am looking to render the bootstrap primary color and inline radio buttons. Form class PersonForm(forms.Form): Gender = forms.ChoiceField(required=True, widget=forms.RadioSelect( attrs={"label":"Gender", "id":"G", "placeholder": "Gender", "class":"form-control form-check"}), choices=genders.items) HTML <div id="G" class="form-control form-check"> <div> <label for="G_0"><input type="radio" name="Gender" value="M" label="Gender" id="G_0" placeholder="Gender" class="form-control form-check" required=""> Male</label> </div> <div> <label for="G_1"><input type="radio" name="Gender" value="F" label="Gender" id="G_1" placeholder="Gender" class="form-control form-check" required=""> Female</label> </div> <div> <label for="G_2"><input type="radio" name="Gender" value="N" label="Gender" id="G_2" placeholder="Gender" class="form-control form-check" required=""> Not-Applicable</label> </div> -
Why does Prefetch perform better than annotation in django?
Hello I made a code to make it irregular. Can someone tell me why prefetch is faster when the prediction should be faster? annotate test: execution time: 6.65 seconds prefetch test: execution time: 3.02 seconds @transaction.atomic() def set_default_like_place_annotate(start, end): start_time = time.time() print(f"Start time: {start_time}") place_query = Place.objects.filter(removed_at__isnull=True).annotate( exist_liking_count=models.Count('place_likers', filter=Q(place_likers__removed_at__isnull=True)))[start:end] for place in place_query: place.liking_count = place.exist_liking_count place.save() end_time = time.time() elapsed_time = end_time - start_time print(f"execution time: {elapsed_time:.2f} seconds") Here is prefetch code @transaction.atomic() def set_default_like_place_prefetch(start, end): start_time = time.time() print(f"Start time: {start_time}") place_query = Place.objects.filter(removed_at__isnull=True).prefetch_related( models.Prefetch( 'place_likers', queryset=LikingPlace.objects.filter(removed_at__isnull=True), to_attr='_place_likers', ))[start:end] for place in place_query: place.liking_count = len(place._place_likers) place.save() end_time = time.time() print(f"End time: {end_time}") print(f"execution time: {end_time - start_time:.2f} seconds") -
In Django, how do I pass custom information from the user signup html form to the models?
In my Django project, I have two types of profiles (person and business). Based on the form a user fills in signup.html (which is very rudimentary right now) one of the types profiles will be created. (My implementation is based on this - section Extending User Model Using a One-To-One Link). models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) company_name = models.TextField(max_length=100, null=True, blank=True) phone_number = models.TextField(max_length=20, null=True, blank=True) is_vendor = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py: class SignupForm(UserCreationForm): class Meta: model = User fields = ('username', 'email', 'password1', 'password2',) username = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': 'Your username', 'class': 'w-full py-4 px-6 rounded-xl' })) ... class BusinessSignupForm(SignupForm): class Meta(SignupForm.Meta): model = User fields = SignupForm.Meta.fields + ('company_name',) company_name = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': 'Company name', 'class': 'w-full py-4 px-6 rounded-xl' })) class PersonSignupForm(SignupForm): class Meta: model = User fields = SignupForm.Meta.fields + ('phone_number',) phone_number = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': 'Phone number', 'class': 'w-full py-4 px-6 rounded-xl' })) views.py: def signup(request): form_personal = PersonSignupForm() form_business = BusinessSignupForm() if request.method == 'POST': if 'personal_account' in request.POST: form = PersonSignupForm(request.POST) elif 'business_account' in request.POST: form = BusinessSignupForm(request.POST) else: return render(request, 'core/signup.html', {'error': 'Invalid … -
How to register Django hooks with PyInstaller
I want to use the Django hooks in Pyinstaller. I have tried the following: python -m PyInstaller --runtime-hook='hook-django.contrib.sessions.py' --runtime-hook='hook-django.core.cache.py' --runtime-hook='hook-django.core.management.py' --runtime-hook='hook-django.db.backends.py' --runtime-hook='hook-django.py' --runtime-hook='hook-django.template.loaders.py' ... --noconfirm --console --clean manage.py But I am getting FileNotFoundError: [Errno 2] No such file or directory: '.../hook-django.*.py' Should I use the additional-hooks-dir parameter even with the built-in hooks, if so what value should I provide? -
getting error "Application not found" whenever i restart my django app on cpanel
Am trying to set up my django app in c-panel but facing a certain. Whenever i restart the app, Am getting the below error No such application (or application not configured) And whenever i edit the app config and click save i get the below error Error KeyError: 'Config does not contain directory: mutoconsults.kimdigitary.com/muto-consults' Below is my app configuration, and cpanel shows my app is already running. enter image description here And if i navigate to the domain name i get the below info it works python 3.9 -
One project (Django 3 with mod_wsgi installed within py 3.8 venv) works but another (Django 5 with mod_wsgi installed within py 3.12) fails
Issue: Internal Server Error with Django and mod_wsgi on Ubuntu Server Setup: Ubuntu 20.04 Python 3.8 for existing project Python 3.12.4 for new project Apache system mod_wsgi installed in respective virtual environments. The system level has been removed. Projects: Existing Project (Working ✅) Directory: /var/www/existing-project/ Python Version: 3.8 Virtual Environment Path: /var/www/existing-project/venv WSGI File Path: /var/www/existing-project/project/project/wsgi.py Apache Configuration: Protocols h2 http/1.1 WSGIApplicationGroup %{GLOBAL} LoadModule wsgi_module "/var/www/existing-project/venv/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi.cpython-38-x86_64-linux-gnu.so" <VirtualHost *:80> ServerAdmin admin@example.com ServerName existing-project.com DocumentRoot /var/www/existing-project/project/ RemoteIPHeader CF-Connecting-IP ErrorLog ${APACHE_LOG_DIR}/existing-project_error.log CustomLog ${APACHE_LOG_DIR}/existing-project_access.log combined <Directory /var/www/existing-project/project/project> <Files wsgi.py> Require all granted </Files> </Directory> Alias /favicon.ico /var/www/existing-project/project/static/images/favicon/favicon.ico Alias /static /var/www/existing-project/project/static <Directory /var/www/existing-project/project/static> Require all granted </Directory> <IfModule mod_expires.c> <FilesMatch "\.(png|jp?g|gif|ico|mp4|wmv|mov|mpeg|css|map|woff?|eot|svg|ttf|js|json|pdf|csv)"> ExpiresActive on ExpiresDefault "access plus 1 year" </FilesMatch> </IfModule> WSGIDaemonProcess existing-project python-home=/var/www/existing-project/venv python-path=/var/www/existing-project/project WSGIProcessGroup existing-project WSGIScriptAlias / /var/www/existing-project/project/project/wsgi.py RewriteEngine on RewriteCond %{SERVER_NAME} =existing-project.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> New Project (Not working ❌) Directory: /var/www/new-project/ Python Version: 3.12.4 Virtual Environment Path: /var/www/new-project/venv WSGI File Path: /var/www/new-project/project/project/wsgi.py Apache Configuration: WSGIApplicationGroup %{GLOBAL} LoadModule wsgi_module "/var/www/new-project/venv/lib/python3.12/site-packages/mod_wsgi/server/mod_wsgi-py312.cpython-312-x86_64-linux-gnu.so" <VirtualHost *:80> ServerAdmin admin@example.com ServerName new-project.com DocumentRoot /var/www/new-project/project/ RemoteIPHeader CF-Connecting-IP # Basic HTTP Authentication <Directory /var/www/new-project/project> AuthType Basic AuthName "Restricted Area" AuthUserFile /etc/apache2/.htpasswd Require valid-user </Directory> ErrorLog ${APACHE_LOG_DIR}/new-project_error.log CustomLog ${APACHE_LOG_DIR}/new-project_access.log combined <Directory /var/www/new-project/project/project> <Files wsgi.py> Require all granted </Files> </Directory> Alias … -
I have been trying to launch an application for about 4 days in Django to Render
`System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\backends\base\base.py", line 275, in ensure_connection self.connect() File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\backends\base\base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\backends\postgresql\base.py", line 277, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: connection to server at "viaduct.proxy.rlwy.net" (35.212.103.87), port 52584 failed: received invalid response to SSL negotiation: I The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1045, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 982, in run self._target(*self._args, **self._kwargs) File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\core\management\commands\runserver.py", line 136, in inner_run self.check_migrations() File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\core\management\base.py", line 581, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\migrations\loader.py", line 58, in init self.build_graph() File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\migrations\recorder.py", line 89, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\migrations\recorder.py", line 63, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\utils\asyncio.py", line … -
How can I pass headers in Swagger UI?
I am trying to hit the API using Django Swagger UI, but I am not getting header in API. I have tried all the answered solutions but I don't know how none of them worked for me. What am I doing wrong? I am using: drf-spectacular v0.26.2 module. Here is my API view: from rest_framework.permissions import IsAuthenticated from drf_spectacular.utils import extend_schema from rest_framework.views import APIView from rest_framework.response import Response authorization_params_in_header = OpenApiParameter( "Authorization", OpenApiTypes.STR, OpenApiParameter.HEADER, required=True ) class ProtectedView(APIView): permission_classes = (IsAuthenticated,) @extend_schema( tags=["Protected"], parameters=[authorization_params_in_header], responses={200: "Success"}, ) def get(self, request): data = {"message": "This is a protected resource"} return Response(data) When I hit the API, even if I put header in the field, Swagger does not pass it in curl also, which you see in picture below. -
Change title (verbose name plural) in custom admin.TabularInline
In my Django admin UI I use a TabularInline like this: class MyCustomInline(admin.TabularInline): # ... def get_queryset(self, request): # ... The overridden functions adds a filter, so that only a subset of related objects is displayed. In the admin UI I get table using the plural of the model class as title, which is wrong in this case. I would like to give it a custom name. I cannot do this for the model itself, because I want to change the title only for this filtered set. Not for the model class in general. I tried to figure it out from the source code. In the template I found out that the verbose_name is passed in via opts, but could not follow its path to find a way to override it. Could somebody give me a hint how to change the title aka verbose name just for this specific TabularInline? -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.User' that has not been installed
I just create Django project and get this error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.User' that has not been installed this my files settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "rest_framework", "api", ] AUTH_USER_MODEL = "api.User" models from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model class User(AbstractUser): ACTIVE = 0 DEACTIVE = 1 STATUS = [ (ACTIVE,"active"), (DEACTIVE,"deActive") ] chatID = models.PositiveBigIntegerField() fname = models.CharField(max_length=20) lname = models.CharField(max_length=20) invitedBy = models.ForeignKey(to=get_user_model(),on_delete=models.PROTECT,default=None) point = models.PositiveBigIntegerField(default=0) team = models.ForeignKey(to=TelegramGroup,on_delete=models.CASCADE) custom_status = models.PositiveSmallIntegerField(choices=STATUS,default=0) def __str__(self) -> str: return self.chatID When I delete all the fields and just set user table like this from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass I get no errors -
Cannot connect to Django app's PostgreSQL database
I am trying to use this app from Github https://github.com/realsuayip/django-sozluk it is a PostgreSQL & Django app that available on port 8000. I installed it and when I open locahost:8000 it successfully opens. But I can't connect the database via DBEAVER or PSQL. connection infos of the App: /conf/django.env DEBUG=0 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 192.168.2.253 CSRF_TRUSTED_ORIGINS=http://127.0.0.1:8000 DJANGO_SETTINGS_MODULE=djdict.settings_prod SQL_ENGINE=django.db.backends.postgresql SQL_PORT=5432 DATABASE=postgres SQL_HOST=db SQL_DATABASE=db_dictionary SQL_USER=db_dictionary_user SQL_PASSWORD=db_dictionary_password EMAIL_HOST=eh EMAIL_PORT=587 EMAIL_HOST_USER=eh_usr EMAIL_HOST_PASSWORD=pw I wrote this command to see which ports are listening: sudo lsof -i -P -n | grep LISTEN and result: systemd-r 665 systemd-resolve 15u IPv4 21662 0t0 TCP 127.0.0.53:53 (LISTEN) systemd-r 665 systemd-resolve 17u IPv4 21664 0t0 TCP 127.0.0.54:53 (LISTEN) cupsd 1435 root 6u IPv6 25882 0t0 TCP [::1]:631 (LISTEN) cupsd 1435 root 7u IPv4 25883 0t0 TCP 127.0.0.1:631 (LISTEN) docker-pr 7811 root 4u IPv4 53897 0t0 TCP *:8000 (LISTEN) docker-pr 7816 root 4u IPv6 53902 0t0 TCP *:8000 (LISTEN) docker-pr 8136 root 4u IPv4 55578 0t0 TCP *:80 (LISTEN) docker-pr 8143 root 4u IPv6 55581 0t0 TCP *:80 (LISTEN) as you see there is no port 5432. however I tried psql command also: psql -U db_dictionary_user result: psql: hata (error): connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: no file or directory Is … -
Can login as superuser but not as normal user
i have made a super user and registering other users. but only able to log in as superuser and when i try to login as normal user its shows "Invalid phone number or password". Can someone help me with this models.py class CustomUserManager(BaseUserManager): def create_user(self, phone_number, email=None, name=None, password=None, **extra_fields): if not phone_number: raise ValueError('The phone number must be set') email = self.normalize_email(email) if email else None user = self.model(phone_number=phone_number, name=name, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone_number, email=None, name=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(phone_number, email, name, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField(unique=True, max_length=20) name = models.CharField(max_length=150, default='') email = models.EmailField(unique=True, blank=True, null=True) is_active = models.BooleanField(default=True) is_superuser=models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) objects = CustomUserManager() USERNAME_FIELD = 'phone_number' EMAIL_FIELD = 'email' def __str__(self): return self.phone_number views.py @api_view(['POST']) def login_api(request): if request.method == 'POST': serializer = LoginSerializer(data=request.data) if serializer.is_valid(): phone_number = serializer.validated_data.get('phone_number') password = serializer.validated_data.get('password') user = authenticate(request, phone_number=phone_number, password=password) if user is not None: if user.is_active: login(request, user) return Response({'message': 'Login successful'}) else: return Response({'error': 'User account is disabled'}, status=status.HTTP_401_UNAUTHORIZED) else: return Response({'error': 'Invalid phone number or password'}, status=status.HTTP_401_UNAUTHORIZED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'error': 'Method not allowed'}, status=status.HTTP_405_METHOD_NOT_ALLOWED) settings.py AUTH_USER_MODEL='detectapp.CustomUser' I made … -
PUT metod make the password field are required and when i put the value in fields its save it as a text in th database with no hash
views.py from .serializers import CreateUser,ShowUser,MeSerializer,ChangePasswordSerializer from rest_framework import viewsets from django.contrib.auth.models import User from rest_framework.decorators import action from rest_framework.response import Response class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() create_serializer_class = CreateUser show_serializer_class = ShowUser # serializer_class = ChangePasswordSerializer def get_serializer_class(self): if self.action in ["list","retrieve"]: return self.show_serializer_class if self.action in ["partial_update","destroy","create","update"]: return self.create_serializer_class return self.serializer_class @action(detail=False,serializer_class=MeSerializer) def me(self, request): self.kwargs["pk"] = request.user.pk return super().retrieve(request) @action(methods=['put'],detail=True,serializer_class=ChangePasswordSerializer ,url_path="change-password") def change_password(self,request,pk=None): super().update(request) return Response({ "stats" : "Password Changed" }) serializers.py from rest_framework import serializers from django.contrib.auth.models import User class CreateUser(serializers.ModelSerializer): password = serializers.CharField(write_only=True) confirm_password = serializers.CharField(write_only=True) class Meta: model = User fields = [ "username", 'first_name', 'last_name', 'email', 'password', 'confirm_password' ] def validate(self, data): password = data.get('password') confirm_password = data.get('confirm_password') if password != confirm_password: raise serializers.ValidationError("The password must match") else: return data def create(self, validated_data): user = User.objects.create( username=validated_data.get('username'), first_name=validated_data.get("first_name"), last_name= validated_data.get("last_name"), email= validated_data.get("email") ) user.set_password(validated_data.get("password")) user.save() return user class ShowUser(serializers.ModelSerializer): class Meta: model = User exclude = [ 'password' ] class MeSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ "id", "username", "first_name", 'last_name', 'email', ] class ChangePasswordSerializer(serializers.ModelSerializer): old_password = serializers.CharField(write_only=True) new_password = serializers.CharField(write_only=True) new_password_confirmation = serializers.CharField(write_only=True) class Meta: model = User fields = [ 'old_password', 'new_password', 'new_password_confirmation' ] def validate_old_password(self, value): user = self.context["request"].user … -
Django create() not applying annotations applied on manager
Imagine the following model, manager and queryset: from django.db import models class BlaQuerySet(models.QuerySet): def annotate_field(self): return self.annotate(bla_field=Value('Bla') class BlaManager(models.Manager): def get_queryset(self): return BlaQuerySet(self.model, using=self._db).annotate_field() class Bla(models.Model): hello = models.CharField(max_length=10) Now that we have the model. Let's create something: bla_instance = Bla.objects.create(hello='something') bla_instance.bla_field returns `AttributeError: 'Bla' object has no attribute 'bla_field' On the other hand, when you filter that item: bla_instance = Bla.objects.get(hello='something') bla_instance.bla_field returns the expected Bla How can I force the create() to use my manager instead of the default one? -
dj-rest-auth with JWT (problem with login functionality)
I have problem with login functionality, when the first time I log in it returns csrf_token, access_token and refresh_token . and it works fine till the expiration time. I know when the access token is expired I should get new one through refresh token but it should also work when I directly use the login route and giving username and password but I get error: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } and when I see the cookies part the previous values are still there shouldn't they be vanished? I think the problem origins from here. when i manually delete them it works fine. and even when the refresh token expires I get the same error, how does it work? -
Using Django Debug Toolbar With DRF, Simple JWT Auth
django-debug-toolbar needs its output to be html, but i am using apis with jwt authentication (djangorestframework-simplejwt). So i am unable to use debug toolbar. I have all the settings of IPs, Middlewares everything correct as per documentation. All my APIs have Authentication and Authorization. All my libraries, modules are in latest versions. I have tried these methods Using django spectacular and creating an Swagger Documentation for my APIs, but it is not generating correct documentation (my apis work on many models, so unable to generate correct schema), Many Schemas are missing and also i dont know why extend_schema is not working. Used django-debug-panel by changing the errors with views.py, urls.py, middleware.py in django-debug-panel and also installed the chrome extension but i dont understand how to use it. Used django-silk but i want to use debug toolbar. Is there anyway i can use django debug toolbar somehow? I want to try again with any new ideas or changing anything in those methods i mentioned -
At least one element of a list and not all element of a list must match for a many to many relationship query in django
Here i have a list of place and tags for a reservation : And i would like a query where at least one of the list of places and at least one of the tags need to match the query slot, and not all places and not all tags need to match for the slot reservation. here is my solution : tags = Tag.objects.filter(name__in=tags) print("tags", tags) places = PartnerPlace.objects.filter(zip_code__in=cps) print("places", places) #slots is a queryset slots = Slot.objects.filter() for place in places: for tag in tags: slots = slots | Slot.objects.filter( tag=tag, place=place, ) It works but i think it's not elegant nor optimal if anyone have a better solution. Regards -
Django for loop not working in HTML in Django 4.2
HELP: There is some issue with for loop in my code. I cannot find the problem. This problem is not displaying data from backend. Can you help me with it? Whole code and process is given below. Models: from django.db import models class ImageGallery(models.Model): Title=models.CharField(max_length=1000, blank=True, null=True) Image=models.ImageField(upload_to='uploaded/photography') Description=models.CharField(max_length=1000, blank=True, null=True) Company=models.CharField(max_length=1000, blank=True, null=True) Admin: from django.contrib import admin from .models import * admin.site.register(ImageGallery) Views: # Galaries wala page def gallery_all(request): img_all = ImageGallery.objects.all() return render(request, 'gallery-all.html',{ 'img_all':img_all, }) HTML: <!-- Main --> <div id="main"> {% for imgraphy in img_all %} <!-- Each Image in gallery --> <article class="thumb"> Test Text <a href="{{imgraphy.Image.url}}" class="image"><img src="{{imgraphy.Image.url}}" alt="" /></a> <h2>{{imgraphy.Title}}</h2> <p>{{imgraphy.description}}</p> </article><!-- Each Image in gallery ends--> {% endfor %} </div> Django Admin: (Image showing data is entered) As you can see, data entered from backend is showing in the admin page but as shown below, there is blank space, why isn't data passing? Please help! Image and text not showing inside loop: -
Razorpay Integration in Django Project payment is not getting completed
I am integrating razorpay in django project. I am creating order through OrderPostApi. This is creating my order and my order_is getting saved in database. But when I call the payment_page view with order id generated in browser I am getting the pay button and when I click on that and after filling details(razorpay test cards for testing), my payment is not getting confirmed. It is showing "Your payment is being processed" for hours. And I am unable to generate the razorpay_payment_id and razorpay_signature in my database. I want when I make the payment, my payment should be completed and I will be able to get the razorpay_payment_id and razorpay_signature in my database. This is what I have done. OrderPostApi: class OrderPostApi(APIView): permission_classes = [AllowAny] Serializer = OrderSerializer def post(self, request, format=None): serializer = self.Serializer(data=request.data) if serializer.is_valid(): #save the order order = serializer.save() #create razorpay client client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET)) #create razorpay order razorpay_order = client.order.create({ 'amount': int(order.total_amount * 100), #amount in paise 'currency':'INR', 'payment_capture':'1' }) #update order with razorpay details order.razorpay_order_id = razorpay_order['id'] order.save() response_data= serializer.data response_data['razorpay_order_id'] = razorpay_order['id'] return Response(response_data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) OrderPaymentStatusApi: class OrderPaymentStatusApi(APIView): permission_classes= [AllowAny] def post(self, request, format=None): data = request.data #verify the … -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb8 in position 57: invalid start byte ERROR when using Django and Postgresql
Hi I'm a newbie developer trying to make a webpage with django and postgresql db. I made a project and app and connected with settings.py to postgresql db. When I run python manage.py makemigrations, this error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb8 in position 57: invalid start byte keeps popping up and I cannot go further into developing my project. psql is running well and psycopg2 is installed into my venv psql version 16 PLEASE HELP!! Check UTF8 encoding in postgresql db. Re-made by db with direct utf8 encoding to my db. Even made new project but still the same problem appears. It does not happen when I use built in sqlite3.