Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django: KeyError at /panel/home/login/ 'HTTP_REFERER'
I have a problem to get the HTTP_REFERER address from django. I want to userauth system in two separate login pages and for that, I set in one of login pages if the url that redirected person to this login page had 'business' word, redirect user into business login page. Thanks for Help I wrote this Code: if 'business' in request.META['HTTP_REFERER']: return redirect('panel_business:login_business') Here is My Error: KeyError at /panel/home/login/ 'HTTP_REFERER' Django Error Full Trace: Environment: Request Method: GET Request URL: http://localhost:8009/panel/home/login/?next=/panel/business/ Django Version: 4.2.6 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', 'panel', 'panel_business'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/arshia/w/recycle/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/arshia/w/recycle/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/arshia/w/recycle/panel/views.py", line 44, in login_home if 'business' in request.META['HTTP_REFERER']: Exception Type: KeyError at /panel/home/login/ Exception Value: 'HTTP_REFERER' -
Advice regarding integrating C# code with django backend
I use C# to convert documents (pdf, docx etc) to other formats (docx, xls, ppt etc) and my backend is written with Python (django) I successfully wrote and loaded a c# dll which let me call it's functions and convert the documents directly from python, using pythonnet clr Issue is, it's slow, like marginally slower (I'd say 20 times slower) than using the same code as if I compiled and ran it as an executable instead of loading it as a dll to python So I need an advice, should I just make the c# code into an executable and then call it via a subprocess with a file path argument (which will force me to write the file into the disk, call the subprocess, which will on turn read the file, and write again, and then the python will read the output file and delete it) or is there alternative? With the dll solution i just pass the file bytes to the dll and don't need to write a file to disk, which would be (for me) a preferable solution, but not at the cost of that big of speed diffrance. Im assuming passing the entire file's contents (bytes) … -
DRF Simple JWT functions RefreshToken.for_user(user) get Attribute error with Custom User Model
I create a custom User Model with usercode is PrimaryKey class User(AbstractBaseUser, PermissionsMixin): usercode = models.CharField(primary_key=True, unique=True, null=False) username = models.CharField(max_length=255, unique=True, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) phone_number = models.CharField(max_length=128, unique=False, null=True, blank=True, default=None) password = models.CharField(max_length=256, null=False) ... I replace default TokenObtainPairView serialier of SimpleJWT with and work quite good class CustomTokenObtainPairSerializer(serializers.Serializer): usercode = serializers.CharField(max_length=64) password = serializers.CharField(max_length=255) def validate(self, attrs): usercode = attrs['usercode'].upper() password = attrs['password'] # Get user object for validating user = User.objects.filter(usercode=usercode).first() # Validating login request if user is None: raise AuthenticationFailed(f'User not found!') if not check_password(password, user.password): return Response({'message': 'Wrong password!'}) user_data = UserSerializer(user).data tokens = get_tokens_for_user(user) return {'user': user_data, 'tokens': tokens} class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } But when I try to get custom token like source Creating tokens manually I got error at RefreshToken.for_user(user) Errors details: AttributeError at /application/api/v1/2024/token/ 'User' object has no attribute 'id' Request Method: POST Request URL: http://127.0.0.1:8000/application/api/v1/2024/token/ Django Version: 5.0.3 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'id' I checked and got that the RefreshToken.for_user require a User model with id is PrimaryKey File "D:\development\py\DJ_Project\venv\Lib\site-packages\rest_framework_simplejwt\tokens.py", line 203, in for_user user_id … -
Creating database in PostgreSQL following Django installation
Forgive me my indolence, but I was following Django installation based on this manual https://idroot.us/install-django-opensuse/ up until to the point where you need to create new database using createdb mydatabase. I am using OpenSuse Tumbleweed Release 20240320 and I have tried this in Python virtual environment. Now, It is giving an obvious error when using createdb mydatabase: "Connection to server on socket "/run/postgresql/.s.PGSQL.5432" failed: No such file or directory. Is the server running locally and accepting connections on that socket?" So I have checked the following: ps -ef | grep postgres It gives me this: root 12831 27003 0 11:18 pts/0 00:00:02 sudo su - postgres root 12833 12831 0 11:18 pts/1 00:00:00 sudo su - postgres root 12834 12833 0 11:18 pts/1 00:00:00 su - postgres postgres 12835 12834 0 11:18 pts/1 00:00:00 -bash postgres 12956 12835 0 11:21 pts/1 00:00:02 yes root 13133 12835 0 11:24 pts/1 00:00:00 sudo su - postgres root 13135 13133 0 11:24 pts/2 00:00:00 sudo su - postgres root 13136 13135 0 11:24 pts/2 00:00:00 su - postgres postgres 13137 13136 0 11:24 pts/2 00:00:00 -bash postgres 14851 13137 99 11:59 pts/2 00:00:00 ps -ef postgres 14852 13137 0 11:59 pts/2 00:00:00 grep … -
Django Load bootstrap modal only after form validation passes
Am trying to pop up a modal window with the terms & conditions, Only when the user accepts the terms and conditions then the data is submitted to the database. I want to validate user input before the modal pops up. Below is my code. individual_account.html <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" id="individualForm"> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field.errors }} {{ hidden_field }} {% endfor %} <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{form.full_name.id_for_label}}"> {{ form.full_name.label }} </label> {{ form.full_name }} {% if form.full_name.errors %} {% for error in form.full_name.errors %} <p class="text-red-600 text-sm italic pb-2">{{ error }}</p> {% endfor %} {% endif %} </div> <div class="w-full md:w-1/2 px-3"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{form.id_passport_no.id_for_label}}"> {{ form.id_passport_no.label}} </label> {{ form.id_passport_no }} {% if form.id_passport_no.errors %} {% for error in form.id_passport_no.errors %} <p class="text-red-600 text-sm italic pb-2">{{ error }}</p> {% endfor %} {% endif %} </div> </div> <!-- Button trigger modal --> <button type="button" class="bg-yellow-700 text-white rounded-none hover:bg-white hover:text-blue-900 hover:border-blue-900 shadow hover:shadow-lg py-2 px-4 border border-gray-900 hover:border-transparent" data-bs-toggle="modal" data-bs-target="#exampleModal"> Create Account </button> <!-- Modal --> <div class="modal fade" …