Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting 401 unauthorised when trying to access JWT authenticated page in Django even after generating token
I'm a student trying to teach myself JWT authentication. I created a basic log in page and after logging in the user should see a welcome page that says Welcome {username}. However even after logging in, the welcome page says Welcome GET /welcome/ HTTP 401 Unauthorized Allow: GET, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer realm="api" { "detail": "Authentication credentials were not provided." } My code looks like this: views.py from django.http import JsonResponse from django.shortcuts import render, redirect from loginapp.models import User from rest_framework.decorators import api_view, permission_classes, authentication_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth import authenticate from rest_framework_simplejwt.authentication import JWTAuthentication from django.urls import reverse def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') print("Username:", username) print("Password:", password) user = User.objects.filter(username=username).first() #user = authenticate(username=username, password=password) if user is not None and user.password == password: refresh = RefreshToken.for_user(user) token = str(refresh.access_token) response = JsonResponse({'message': 'Login successful'}) response['Authorization'] = f'Bearer {token}' return response else: return JsonResponse({'error_message': 'Invalid username or password.'}, status=400) else: return render(request, 'login.html') @api_view(['GET']) @permission_classes([IsAuthenticated]) def welcome(request): username = request.user.username return Response({'message': f'Welcome, {username}!'}) my urls.py looks like this: from django.urls import path from loginapp import views from rest_framework_simplejwt.views … -
Deploying django app using almalinux 8 plesk
Recently i have created a website using django. But when it is time for deploying it became a nightmare. I am pretty new in these stuff. Since this is a productuon promissed for someone else i have to do it done. I wonder if anyone could do it for me? I have a vps server running using plesk panel. And an almalinux 8 as os. Any help would absolutely work. -
Django annotate over multi records forignkeys
I Work on a KPI system in which every manager can put specific questions for each user and answer them every month from 1 to 10 we have 4 departments, and every department says to have 4 question these answers have to be calculated to return the % number for each department Models # question to answer every month class Question(models.Model): department = models.CharField(max_length=100, choices=USER_TYPE) question = models.CharField(max_length=100) def __str__(self): return f"{self.question}" # create every 01-month celery class Kpi(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="kip_for") created_at = models.DateField() class Meta: unique_together = ("user", "created_at") def __str__(self): return f"{self.user} for Month {self.created_at.month}" # group the answers by department class DepartmentsKPI(models.Model): department = models.CharField(max_length=100, choices=USER_TYPE) kpi = models.ForeignKey( Kpi, on_delete=models.CASCADE, related_name="department_kpi" ) class Answer(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="answer_for" ) score = models.PositiveSmallIntegerField(default=0) comment = models.TextField(null=True, blank=True) kpi_answers = models.ForeignKey( DepartmentsKPI, on_delete=models.CASCADE, related_name="department_answers", ) the problem is when I apply the annotation over the KPI model to sum the answer score for each department, the result becomes ungrouped so I have to group them by a unique value in my case the username def get_kpi_range(*, year, month): queryset = ( KPIRepository.filter_kpis( created_at__year=year, created_at__month=month, ) .prefetch_related("department_kpi__department_answers") .annotate( score=Sum("department_kpi__department_answers__score") / Count("department_kpi__department_answers"), department=F("department_kpi__department"), ) .values("id", … -
About page on Django app is showing Page not found
Tried running about page on a Django project using sublime text editor. The project shows page not found each time i refresh the browser. I have tried every method i came across. from.django contrib import admin from django.urls import path from . import views urlpatterns=[ path('admin/' admin.site.urls) path('about/' views.urls) ]` I expect the project to show the content of the about page. Without returning the 404 error response. from django.http import HttpResponse def index(request): return HttpResponse("This is about page.") -
How to Clean an Ubuntu Server Previously Used for Hosting a Django Project?
I have an Ubuntu server that previously hosted a Django project. I want to clean the server and prepare it for a new project deployment. This includes removing all project-specific files, configurations, and any leftover services related to the old project. Ideally, I'd like to get the server close to its initial state (without reinstalling the OS). I followed the documentation provided by DigitalOcean to set up Django with Postgres, Nginx, and Gunicorn on Ubuntu for the old project. However, now I need to remove all traces of the old project from the server. I'm expecting guidance on how to properly clean up the server, including removing project files, configurations, and services, without affecting the OS or other applications running on the server. DigitalOcean documentation -
Errors with Django 4.2 and Spatialite 5
I am upgrading an application from Django 3.2 to 4.2, which uses postgis in production, and spatialite when running unit tests. Running the tests on this application, I'm getting this error: django.db.utils.OperationalError: error in trigger ISO_metadata_reference_row_id_value_insert: no such column: rowid make: *** [django.mk:49: test] Error 1 This problem is documented in this ticket, and seems to be an issue with using Django 4.2 and Spatialite 5: https://code.djangoproject.com/ticket/32935 One of the workarounds looks like executing this command in the spatialite database: ./manage.py shell -c "import django;django.db.connection.cursor().execute('SELECT InitSpatialMetaData(1);')"; However, after I run this command, I am still getting the no such column: rowid error. Has anyone else run into this? I am using Django 4.2.11, sqlite 3.42.0, libspatialite 5.0.1, python 3.12.2 on Fedora Linux. -
Error when using python3 manage.py makemigrations [closed]
I keep getting this error and don't know what's wrong or what to do. Traceback (most recent call last): File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 717, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/management/base.py", line 453, in execute self.check() File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 495, in check messages.extend(check_resolver(pattern)) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/project/xrwvm-fullstack_developer_capstone/server/djangoenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 725, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'djangoapp.urls' from '/home/project/xrwvm-fullstack_developer_capstone/server/djangoapp/urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the … -
Why the data batch size for loop failing for Insert API in python Django?
We are using 3rd party API to pull data and enabled pagination, hence the amount of data coming in are huge. Some times 12000 records at a time in a list. We are using mySQL DB, and it fails when it receives that amount of data at a time. So, as temporary solution I wanted to implement the "batch size" concept as below: batch_size = 3 for batch in range(0, len(payload), batch_size): batch_data = payload[batch:batch + batch_size] Below is the POST method code snippet where we are getting the data source and its format , and how I am passing it. def post(self, request): data = fetch_data.get(request=request) try: if data.status_code == status.HTTP_200_OK: payload = data.data payload["token_id"] = token_id payload["org"] = org api_log( msg=f"TOtal cont data from xyz : {json.dumps(payload)}" ) api_log( msg=f"Size of cont data from xyz : {len(json.dumps(payload))}" ) api_log( msg=f"Length of cont data to db: {len(payload)}" ) api_log( msg=f"Total cont data to DB: {payload}" ) url = ("http://example.com") batch_size = 3 api_log(msg=f"[BATCH SIZE]:: {batch_size}") for batch in range(0, len(payload), batch_size): api_log(msg=f"[BATCH SIZE]:: {batch_size}") api_log(msg=f"[BATCH]:: {batch}") batch_data = payload[batch:batch + batch_size] api_log(msg=f"[BATCH DATA]:: {batch_data}") response_data = requests.post( url, json=batch_data, ) if response_data.status_code == status.HTTP_201_CREATED: api_log( msg="data inserted successfully" ) … -
Django Rest API - handling max_decimal_places more gracefully
Using Django Rest Framework and having a model that contains a decimal field like this: rate = models.DecimalField(max_digits=7, decimal_places=2) If a rate value is submitded with more than 2 decimal places I get a validation error with code "max_decimal_places". I would like to handle things more gracefully and instead of raising an error I would like to round the rate to 2 decimal places. What's the best or even a good way of doing this. Overriding validation? Other options? Thanks Stephan -
Django PyCryptodome AES decryption - ValueError: Padding is incorrect
I am trying to encrypt incoming files and than decrypt them later. I was following the documentation for how to use AES with CBC mode for decryption and encryption. My view for uploading and encrypting file: @router.post("/upload_files") def upload_files(request, file: UploadedFile = File(...)): save_file = operations.aes_encryption(user_id=request.auth.id,file=request.FILES.get('file')) def aes_encryption(self,user_id,file): user = UserQueries.get_user(id=user_id) key: bytes = bytes(user.key, "utf-8") path: str = user.path save_file = self._encrypt_file(file,key,path,user) return save_file def _encrypt_file(self,file,key,path,user): file_content = file.read() cipher = AES.new(key, AES.MODE_CBC) ct_bytes = cipher.encrypt(pad(file_content, AES.block_size)) iv = b64encode(cipher.iv).decode('utf-8') ct = b64encode(ct_bytes).decode('utf-8') with open(str(settings.BASE_STORAGE_DIR)+"/"+path+file.name,"wb") as f: f.write(ct.encode('utf-8')) return save_metadata This code works like it should it encrypts the file and stores it in directory. My key and iv is stored in database as string. This is my decryption function where I am having trouble: def aes_decryption(self,request, file_id): user = UserQueries.get_user(id=request.auth.id) file = FileQueries.get_file_data(id=file_id) iv = b64decode(file.iv) key = b64decode(user.key) with open(str(settings.BASE_STORAGE_DIR)+"/"+file.path,"rb") as f: cipher = f.read() decrypt_file = self._decrypt_file(iv,key,cipher_text=cipher) def _decrypt_file(self,iv,key,cipher_text): cipher = AES.new(key, AES.MODE_CBC, iv) pt = unpad(cipher.decrypt(cipher_text), AES.block_size) When calling the decryption I am getting this error: Padding is incorrect. Traceback (most recent call last): File "/Users/Library/Caches/pypoetry/virtualenvs/cloud-hub-backend-y-HyWMBZ-py3.11/lib/python3.11/site-packages/ninja/operation.py", line 107, in run result = self.view_func(request, **values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/Documents/cloud_project/backend/cloud_hub_backend/cloud_hub_backend/apps/file_storage/views.py", line 67, in download_files file, content_type, file_name = … -
Django ORM: .filter() finds record but .get() with same query parameters does not
I am doing an ORM query using the .filter without the timeframe specified which returns two records. then I print those record column values to ensure I am not making any mismatches but then when I use the exact same values on the .GET method I get DoesNotExist error even though it just printed that record. Please verify if your comment is valid based on the printed statements before submitting stupid comments like: mAyBe yOu mAde A sPelLinG erRoR?! here is are the prints: Filter Query: timeframe=H4, symbol=XAUUSD, time=2024-04-10 14:00:00+00:00 Filter Record 2: XAUUSD, 2024-04-10 14:00:00, H4 GET Query: timeframe=H4, symbol=XAUUSD, time=2024-04-10 14:00:00+00:00 No record found. @csrf_exempt @require_http_methods(["POST"]) def get_label_data(request): data = json.loads(request.body) data = data.get('data') timestamp = data.get('timestamp') symbol_name = data.get('symbol') label_name_str = data.get('label_name') timeframe = data.get('timeframe') symbol = Symbol.objects.get(name=symbol_name) datetime_stamp = datetime.fromtimestamp(timestamp, tz=pytz.UTC) print(f"Filter Query: timeframe={timeframe}, symbol={symbol_name}, time={datetime_stamp}") forex_ohlc = ForexOHLC.objects.filter(symbol=symbol, time=datetime_stamp) forex_ohlc = list(forex_ohlc)[1] print(f"Filter Record 2: {forex_ohlc.symbol.name}, {forex_ohlc.time}, {timeframe}") print(f"GET Query: timeframe={timeframe}, symbol={symbol_name}, time={datetime_stamp}") try: forex_ohlc = ForexOHLC.objects.get(symbol=symbol, time=datetime_stamp, timeframe=timeframe) except ForexOHLC.DoesNotExist: print("No record found.") except ForexOHLC.MultipleObjectsReturned: print("Multiple records found.") except Exception as e: print(f"An unexpected error occurred: {e}") try: labels = TickLabel.objects.get(forex_ohlc=forex_ohlc, symbol=symbol, label_name__name=label_name_str) return JsonResponse({ 'label_name': labels.label_name.name, 'label_type': labels.label_type.name, 'hasLabel': True }) except TickLabel.DoesNotExist: … -
Exception Type: ValueError: node array from the pickle has an incompatible dtype
So I copied a DjangoML project from Github. The ML model is essentially a diagnosis system that predicts whether or not a patient is at risk based on the values of their blood tests. I'm running this project locally in VSCode but have yet to deploy the backend/ML model. I encountered this problem while attempting to forecast the outcome in the web browser. I'm using Python 3.11.0 for this project. The requirements.txt file includes: asgiref==3.5.0 Django==4.0.3 joblib==1.1.0 numpy~=1.26.4 pandas==2.2.2 python-dateutil==2.8.2 pytz==2022.1 scikit-learn==1.0.2 scipy==1.8.0 six==1.16.0 sklearn==0.0 sqlparse==0.4.2 threadpoolctl==3.1.0 tzdata==2021.5 `Traceback (most recent call last): File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django_MachineLearning_HealthcareApp-main\backend\views.py", line 76, in lpredictor result = ValuePredictor(llis, 7, mname) File "D:\Django_MachineLearning_HealthcareApp-main\backend\views.py", line 60, in ValuePredictor trained_model = joblib.load(rf'{mdname}_model.pkl') File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\joblib\numpy_pickle.py", line 658, in load obj = _unpickle(fobj, filename, mmap_mode) File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\joblib\numpy_pickle.py", line 577, in _unpickle obj = unpickler.load() File "C:\Users\vanda\AppData\Local\Programs\Python\Python311\Lib\pickle.py", line 1213, in load dispatch[key[0]](self) File "D:\Django_MachineLearning_HealthcareApp-main\venv\Lib\site-packages\joblib\numpy_pickle.py", line 402, in load_build Unpickler.load_build(self) File "C:\Users\vang\AppData\Local\Programs\Python\Python311\Lib\pickle.py", line 1718, in load_build setstate(state) File "sklearn\tree\_tree.pyx", line 865, in sklearn.tree._tree.Tree.setstate <source code not available> File "sklearn\tree\_tree.pyx", line 1571, in sklearn.tree._tree._check_node_ndarray <source code not available> Exception Type: ValueError at /diagnose/liver/report Exception … -
Wagtail: include custom form in SnippetsViewSet
I'am trying to include a custom form in the SnippetsView of one of my models.The form's purpose is to let the user upload a csv-file to add Data, the model in question has a one-to-many relationship with a second model, which is then bulk-updated with the data from the csv-file. Th goal is that for very view of every instance of the model generated via the SnippetViewSet the form can be found and used in a seperate Tab created via TabbedInterface. I can of course add manually a form via @hooks.register in a SubMenuItem or I can just add a new FileField to my model and add a hook or overide the models's save method, so that if the user uploads a file in the wagtail-admin it will get used to update the second model. I'd like rather to know wether there is a simple way to add a custom form to a SnippetView without having to subclass wagtail.snippets.views.snippets.EditView and CreateView and creating a new template or at least one not involving to much ducktaping. Currently I can upload the model via csv in the django-admin. But I'd like that to be possible in wagtail-admin as well. -
ModuleNotFoundError: No module named 'captcha.fields'
By Executing command python manage.py runserver in vscode terminal occured this error : Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner self.run() File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run self._target(*self._args, **self._kwargs) File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 486, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ ...... File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "D:\<project path>\porsline\urls.py", line 10, in <module> path('', include('survey.urls')), ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\urls\conf.py", line 39, in include urlconf_module = import_module(urlconf_module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "D:\<project path>\survey\urls.py", line 2, in <module> from . import views File "D:\<project path>\survey\views.py", line 14, in <module> from . forms import CreateSurveyForm, CreateQuestionForm, ShowSurveyForm File "D:\<project path>\survey\forms.py", line 11, in <module> from captcha.fields import CaptchaField ModuleNotFoundError: No module named 'captcha.fields' … -
How to properly use javascript within oTree / django?
I have a problem regarding implementing my non-oTree HTML, CSS, JS files into oTree format. I have this puzzle game (see screenshot 1) . Implemented in oTree it is buggy - as you can see in screenshot 2 . The JS logic kinda works as the counter recognises clicks on the here empty and buggy structured picture pieces. The JS code lies within the PuzzelPage.html file like this {{ block scripts }} <script> var turns = 0; // Zähler für die Anzahl der Züge var puzzleSolved = false; // Zustand des Puzzles var timer; // Globale Variable für den Timer var currTile, otherTile; // Variablen für die aktuellen Puzzle-Teile // Diese Funktion mischt ein Array in einer zufälligen Reihenfolge function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } // Diese Funktion wird aufgerufen, sobald das Fenster geladen ist window.onload = function() { let imgOrder = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; shuffleArray(imgOrder); // Erstelle die Puzzle-Teile und füge sie zum Board hinzu for (let r = 0; r < 3; r++) { for … -
Setting Timezone for django connection
The Problem: Postgresql timezone is set to 'UTC' /etc/postgresql/15/main/conf.d/local.conf: log_timezone = Europe/Warsaw timezone = UTC database has been altered: ALTER DATABASE example_database SET TIMEZONE TO 'Europe/Warsaw'; Postgresql user has set own time_zone SELECT rolconfig FROM pg_roles WHERE rolname = 'someuser'; {TimeZone=Europe/Warsaw} settings.py USE_TZ = True TIME_ZONE = 'Europe/Warsaw' but during connection postgresql is getting: LOG: statement: SELECT set_config('TimeZone', 'UTC', false) What am I doing wrong??? -
Trying to connect oracle db to the django application using wallet.zip file
I'm configuring my Oracle database to the django application using wallet.zip file in the following way. Note: This wallet.zip file contains tnsnames.ora file. In settings.py file: DATABASES = { "oracledb": { "ENGINE": "django.db.backends.oracle", "NAME": "dummyemployee", "USER": "dummyuser123", "PASSWORD": "dummypass123", "OPTIONS": { "wallet_location": "C:\\Users\\Administrator\\Desktop\\Wallet_Location" } } } But when I try to execute the API. It's returning the following error: "wallet_location is an invalid keyword argument for this function" -
Persist list inside a object Django Rest Framework
I'm trying to persiste list of a python object (dico) like this but it's difficult { "leader": { "nameLastname": "AAAAA" }, "employeeRemun": { "grossSalaryBase": 111, "bonuses": 222, "travellingExpenses": 333, "noRemuneration": false }, "abandonmentCurrentAccount": { "abandonDate": "2023-10-20", "partner": "BBB", "amount": 444, "recoveryDate": "2023-10-04", "recoveryAmount": 5555, "abortTime": "-16 jours" }, "commentReviewDuring": { "review": "COMMENT DURING" }, "commentReviewAfter": { "review": "COMMENT AFTER" }, "list_benefits": [ { "natureAvantage": { "actualAmount": 42354, "previousAmount": 53234 }, "leaderAvantage": { "nameLastname": "AAAAA" }, "typeAvantage": { "benefitType": "Private Jet" } }, { "natureAvantage": { "actualAmount": 43532, "previousAmount": 4324 }, "leaderAvantage": { "nameLastname": "AAAAA" }, "typeAvantage": { "benefitType": "Rolls Royce" } } ] } Patch Methode: At beginning i try to do this but i don't find how to access index of list ('HERE') : I try to acces element inside the request with request.data.get(...) but for the natureAvantage it's not a {} but a [] need to be acces by a index for indexLls in llsByIdSerialized.data['naturalBenefits']: benefitTypeById = AvantageNatureDirigeant.objects.get(id=indexLls) benefitRefresh = LeaderBenefeitTypeSerilizer(instance=benefitTypeById, data=request.data.get('remSection', {}).get('list_benefits', {}).get('natureAvantage', {})) if benefitRefresh.is_valid(): benefitRefresh.save() So i try to do this one : Create a seperated object for index, benefit_data in enumerate(request.data.get('remSection', {}).get('list_benefits', [])): actual_amount = benefit_data.get('natureAvantage', {}).get('actualAmount') previous_amount = benefit_data.get('natureAvantage', {}).get('previousAmount') data_to_serialize = { … -
Fetching Data from a .sql file in a Django Project
I have a django project. I have a dump of the data from a Mysql database in a .sql file and want to query some data from this file into my django project and display it. I am fairly new to django. Need some help My settings.py looks like this : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '3306', } } -
DLL load failed while importing _rust: The specified procedure could not be found
I am trying to hit an API that is of POST type, it generates access and refresh tokens which can be used to access other APIs. It takes the username and password in the body, which we generate while creating a superuser (admin) in Django. This is the detailed error I'm encountering while hitting the API in Postman: Internal Server Error: /api/token/ Traceback (most recent call last): File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework_simplejwt\views.py", line 44, in post serializer.is_valid(raise_exception=True) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\serializers.py", line 223, in is_valid self._validated_data = self.run_validation(self.initial_data) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\serializers.py", line 445, in run_validation value = self.validate(value) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework_simplejwt\serializers.py", line 77, in validate data["refresh"] = str(refresh) File … -
How can I fix my blacklist token at Django rest framework simple JWT? Error: Given token not valid for any token type"
Im using rest framework simple_jwt to login, everything works to register, login im having the access and refresh token. When I check on the website of JWT Web tokens, It says that the token has type "refresh", the same that I should pass to the Bearer Authorization on postman. But I'm facing this error if the fresh token after login that im passing: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token has wrong type" } ] } My code: LogoutSerializer: class LogoutUserSerializer(serializers.Serializer): refresh_token = serializers.CharField() default_error_message = {"bad_token": ("Token is invalid or has expired")} def validate(self, attrs): self.token = attrs.get("refresh_token") # Corrected accessing the attribute try: # Ensure the token is not empty if not self.token: raise serializers.ValidationError("Token is required") # Check if the token is valid token = RefreshToken(self.token) # Ensure the token is a refresh token if token.token_type != "refresh": raise serializers.ValidationError( "Given token not valid for refresh token type" ) except TokenError: raise serializers.ValidationError("Token is invalid or has expired") return attrs def save(self, **kwargs): try: token = RefreshToken(self.token) token.blacklist() except TokenError: return self.fail("bad_token") LogoutView: class LogoutUserView(GenericAPIView): serializer_class = LogoutUserSerializer permission_classes = [IsAuthenticated] def post(self, … -
`I am trying to build a registration form in Django, using Django form
i put {{form.username}} {{ form.email }} {{ form.password }} in my html code instead of text boxes and i can't see them, i also made a forms.py file and views.py this is register.html `{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Registration</title> <link rel="stylesheet" href="{% static "register.css" %}"> </head> <body> <div class="container"> <h2>User Registration</h2> <form action="" method="post"> {% csrf_token %} <div class="form-group"> <label for="username">Username:</label> {{form.username}} </div> <div class="form-group"> <label for="email">Email:</label> {{ form.email }} </div> <div class="form-group"> <label for="password">Password:</label> {{ form.password }} </div> <div class="form-group"> <button type="submit">Register</button> </div> </form> </div> </body> </html>` this is forms.py `from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class CreateUserForm(UserCreationForm): class Meta: model = User fields =[ 'username', 'email', 'password']` this is views.py `def register(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return render(request, 'register.html')` I tried debugging, wathing a tutorial and asking chat gpt and i couldn't fix it -
Django guest user cart functionality? Is it safe?
Creating an e-commerce website project to try and learn Django and more about Javascript, so I have been going over a tutorial for the past week. In the tutorial, there is a guest user cart feature. It works by storing user and product data into the cookies. Though, I am having trouble getting it to add multiple of the same item. If I were to login as a user the website works fine. The remove feature works fine for deleting an item out of the cart as guest. In the JavaScript console, the items in the cart get deleted, but the cookies retain the same information before the website reloads. Don't know the cause for this issue. I would really like this feature to work out. JavaScript Console Log cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function() { //sets variable to add to the dictionary. var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) //checks to see if the user is logged in. console.log('USER:', user) if (user === 'AnonymousUser') { addCookieItem(productId, action) } else { updateUserOrder(productId, action) } }) } function addCookieItem(productId, action) { console.log('Not logged in.') //add quantity … -
TokenObtainPairSerializer override
i'am using django-otp and Django-rest-jwt my goal is I want to check if user has enable 2fa if yes I will give him the refresh and access token i would like to change my top file to not required . class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['otp'] = OtpField() def validate(self, attrs: Dict[str, Any]) -> Dict[str, str]: data = super().validate(attrs) user_logged_in.send(sender=self.user.__class__,request=self.context['request'],user=self.user) if self.user is None: user_login_failed.send(sender=self.user.__class__,request=self.context['request'],user=self.user) return data -
Deployed Django Application on PythonAnywhere: Connection Refused Error When Controlling Raspberry Pi Robot Remotely
I am trying to deploy a Django web application on PythonAnywhere that controls a Raspberry Pi robot remotely. The application worked flawlessly locally using ngrok to establish a connection, but after deploying it to PythonAnywhere, I encountered the following error: 2024-04-17 07:49:53 Connection refused: The server is not accepting connections. I tried: Added localhost to the ALLOWED_HOSTS in Django settings. Tried running the server on a different port. Disabled the firewall on the Raspberry Pi. Added corsheaders to the Django project.