Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Save the current user for the created model object in django rest framework
Sorry if I'm asking a noob question. i have this model which used to create a article and the article has a field which associated to the django user model from django.db import models from django.contrib.auth.models import User class Article(models.Model): headline = models.CharField(max_length=150) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateField(auto_now_add=True) pub_time = models.TimeField(auto_now_add=True) # fields need to be added # location # byline -> line tells who writes the article # conclusion # tags def __str__(self): return self.headline i use this django rest framework view to create the object. using postman and giving the author id i can create the article post @api_view(['POST']) def create(request): if request.method == 'POST': serializer = ArticleSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) what i need to achieve is the only the logged user need to be able to create the article and when the user create the article the author id need to be auto updated at the time the object was created. here is my serializer from rest_framework import serializers from . models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' -
youtube transcript summariser using chrome extension project
In youtube transcript summariser using chrome extension , im getting warning as " This is a development server. Do not use it in a production deployment. Use a production WSGI server instead". im not understanding what to do -
django-channels: Not Found: /ws/
Hi I have typical django app for real-time notifications using websockets Have 2 apps "core" and "notification" I need to show notification on notification page when Review is created. I added channels core and notification to installed apps INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "channels", "core", "notification", ] Added asgi configuration ASGI_APPLICATION = "reviewproject.asgi.application" Configured channel layers CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } Here is asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import notification.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "reviewproject.settings") application = ProtocolTypeRouter( { "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( notification.routing.websocket_urlpattern ) ) } ) I also have routing.py from django.urls import re_path from . import consumers websocket_urlpattern = [ re_path(r'ws/notification/$', consumers.NotificationConsumer.as_asgi()), ] consumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = "notification" await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() async def disconnect(self): await self.channel_layer.group_discard(self.group_name, self.channel_name) async def send_message(self, event): message = event['message'] await self.send(text_data=json.dumps({'message': message})) And sending notification when Review is created class ProductView(View): def send_notification(self, message): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("notification", {"type": "send_message", "message": message}) def get(self, request, pk): reviews = ReviewModel.objects.filter(product=pk) product = get_object_or_404(ProductModel, pk=pk) context = { "reviews": reviews, "product": product } return render(request, … -
I am Unable to Vailidate error to my UI I want the specific error as if username is same the error will be username doesn't exist
I am Unable to Vailidate error to my UI I want the specific error as if username is same the error will be username doesn't exist My Backend code My Urls.py from django.urls import path from . views import * from rest_framework_simplejwt.views import ( TokenRefreshView, ) urlpatterns = [ path('', getRoutes), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('register/', UserRegistrationView.as_view(), name='user_registration'), ] I have simple serializer My Serializers.py from rest_framework import serializers from django.contrib.auth.models import User class UserRegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email', 'password'] My Views.py from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from django.contrib.auth.models import User from rest_framework import status from rest_framework.views import APIView from .serializer import UserRegistrationSerializer from django.core.exceptions import ValidationError class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username # ... return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer @api_view(['GET']) def getRoutes(request): routes = [ '/api/token', '/api/token/refresh', ] return Response(routes) class UserRegistrationView(APIView): def post(self, request): serializer = UserRegistrationSerializer(data=request.data) if serializer.is_valid(): username = serializer.validated_data['username'] password = serializer.validated_data['password'] email = serializer.validated_data['email'] phone = serializer.validated_data['phone'] # Check if username already exists if User.objects.filter(username=username).exists(): return Response({'error': 'Username already exists'}, status=status.HTTP_400_BAD_REQUEST) # Check if … -
I have a question about generic view in Django's tutorial example
In the “Writing your first Django app, part 4” of the tutorial of Django documentation, there is example of using generic view like blow ; File name : polls/views.py class IndexView(generic.ListView): template_name = "polls/index.html" context_object_name = "latest_question_list" def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by("-pub_date")[:5] class DetailView(generic.DetailView): model = Question template_name = "polls/detail.html" class ResultsView(generic.DetailView): model = Question template_name = "polls/results.html"` Q1 .in “class IndexView”, where is the “latest_question_list” defined? Is it the return value of “get_queryset” function? If so, how can I find the relationship between “latest_question_list”and “get_queryset” function? There is not any clue. Q2.there is a explanation in the tutorial like so: In previous parts of the tutorial, the templates have been provided with a context that contains the question and latest_question_list context variables. For DetailView the question variable is provided automatically – since we’re using a Django model (Question), Django is able to determine an appropriate name for the context variable. However, for ListView, the automatically generated context variable is question_list. To override this we provide the context_object_name attribute, specifying that we want to use latest_question_list instead. My question is that, it said the question variable is provided automatically for DetailVIew. what does the “question” … -
Distribution of values by days from the database in the template
I'm trying to distribute the data in this form: August 1st: value 1 value 2 August 2: value 3 value 4 My model: class MyModel(models.Model): value = models.CharField('Value', max_length=150) date = models.DateTimeField('Date', auto_now_add=True) -
CS50W mail project, mark my read variable in my API as true as default but it must be false
I've been dealing with this bug for past few days and i can't fix it. So basically in this project i should make a email in a local host server using only JS, HTML and css. as you can see in the following code the read variable of the emails that get composed must remain false as default until you visit the email page : models.py : class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "read": self.read, "archived": self.archived } and it's not my JS file problem because i never even write anything for the read variable to change it : Inbox.js file : document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector('#submit').addEventListener('click', submit); // By default, load the inbox load_mailbox('inbox'); }); function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display … -
Passing function from DjangoListAPI to a celery task
I am having some trouble passing a function to a celery task, and i cant pass its results because it takes much time to load and it times out the api request @celery.task(name='task_name', bind=True) def celery_task(self, headers, data_function): data = data_function() # more code class DataClass(generics.ListCreateAPIView): def get(self, request, *args, **kwargs): send_excel_as_email.apply_async(args=[headers, self.get_data]) def get_data(self): queryset = self.filter_queryset(self.get_queryset()) serializer_class = self.get_serializer_class() data = serializer_class(queryset, context=self.get_serializer_context(), many=True).data # more code So basically the celery_task is a reusable task that will be used in many other Classes and each class has its own query_set and serializer, thats why i need to find a way to call the get_data function inside the celery task itself i tried using pickl but it throwed errors that it cant serialize the function -
Can't figure out why Django ORM is giving me this error with prefetch_related()
I have the following data models in my Django app: class Company(models.Model): company_name = models.CharField(max_length=255) company_url = models.URLField(max_length=2048, blank=True, null=True) ... class Meta: db_table = 'company_table' class PricingPlan(models.Model): plan_name = models.CharField(max_length=255, blank=True, null=True) ... company = models.ForeignKey(Company, related_name='pricing_plans', on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'pricing_plan_table' class Feature(models.Model): feature_name = models.TextField(blank=True, null=True) plans = models.ManyToManyField(PricingPlan, related_name='features', blank=True) class Meta: db_table = 'feature_table' class WebData(models.Model): company = models.OneToOneField(Company, related_name='web_data', on_delete=models.CASCADE) version = models.IntegerField(blank=True, null=True) ... class Meta: db_table = 'web_data_table' Now, I want to query the DB like this: queryset = queryset.select_related('web_data').prefetch_related('pricing_plans', 'pricing_plans__features') But get this error: django.db.utils.ProgrammingError: relation "feature_table_plans" does not exist LINE 1: ...e"."feature_name" FROM "feature_table" INNER JOIN "feature_t... Any ideas on how to fix this? -
Deploying a complete full stack app to Railway
I have a full containerized frontend React app, I also have a full containerized backend Django/Python app (this simply works as an API) which accesses a Postgres database, and a third project which uses a Docker image of Postgres. I also have the full project using Docker Compose. What do you suggest that I do in order to deploy it to the Railway hosting: Deploy it to Railway using the complete Docker Compose project Deploy the React frontend, also deploy the Django/Python backend and also deploy the Postgres project Deploy just the frontend and backend, and use some sort of Postgres service that Railway could have I don't know which approach to take and which is viable. -
How can I exclude a subclass (or subclasses) of pages from Wagtail's search functionality?
I'm creating a blog site for a friend and there are certain page models that I would like to be excluded from users' searches. These models are BlogIndexPage and ThankYouPage. Both of these models subclass wagtail.models.Page. I want to have control over how these pages are visited and therefore don't want links for them to show up in search results if users search—for example—thank or blog. For context, this is the search view function: def search(request): search_query = request.GET.get("query", None) page = request.GET.get("page", 1) # Search if search_query: search_results = ( Page.objects.live().order_by("-first_published_at").search(search_query) ) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = Page.objects.none() # etc... I've tried the two solutions suggested in this other thread and a third solution I found in the documentation, but they did not solve my problem. Specifically I tried the following: class ThankYouPage(Page): ... # Method One: @classmethod def get_indexed_objects(cls): return cls.objects.none() # Method Two: def get_indexed_instance(self): return None # Method Three: search_fields = [] I ran the update_index management command after each change. In the Django shell, I get the following behavior: >>> from wagtail.models import Page >>> from apps.contact.models import ThankYouPage >>> >>> Page.objects.all().search("thank") <SearchResults [<Page: Thank You Page>]> >>> >>> ThankYouPage.objects.all().search("thank") … -
How to define file path in a view method in django views.py
I need to read a CSV file in my view method. This is my view method in views.py in django project: def myfile(request): csv_fp = open('file.csv', 'r') reader = csv.DictReader(csv_fp) headers = [col for col in reader.fieldnames] out = [row for row in reader] return render(request, 'myfile.html', {'data' : out, 'headers' : headers}) This is in my urls.py: path('myfile/', views.myfile, name='myfile'), My django version is: 3.2.2 I tried many ways to open file in csv_fp = open('file.csv', 'r'). I used the below ways in my views.py and non of them worked: my file in the static directory: csv_fp = open('static/file.csv' , 'r') # not working csv_fp = open('file.csv' , 'r') # not working I added the below lines in my views.py and it didn't work as well: import csv, os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR, 'static') file_path = os.path.join(STATIC_ROOT, 'file.csv') csv_fp = open(file_path , 'r') This is the error message: Exception Location: /home/djangoir/virtualenv/project/3.7/lib/python3.7/site-packages/django/template/loader.py, line 19, in get_template The point is I don't want to generate a model for the database and import CSV file into the database. I just need somehow read the file and export its data in a dictionary in the render method. -
Sending foreign key as argument resulting in This Field is Required Error
I am trying to create an app where Users can login and create tasks. The code for my django app is hosted here I am using JWT authentication and drf-yasg to generate swagger. So the TaskSerializer takes 3 arguments taskname which is a string completion which is a boolean username which should point to the user model My TaskModel is as follows class Tasks(models.Model): taskname=models.CharField(max_length=10) completion=models.BooleanField(default=False) username = models.ForeignKey(User, on_delete=models.CASCADE) My TaskSerializer is class TaskSerializer(serializers.ModelSerializer): class Meta: model = Tasks fields = ['taskname', 'completion', 'username'] My TaskView is as follows: class TaskView(APIView): def get(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') tasks = Tasks.objects.filter(username=payload['username']).all() return Response(tasks) @swagger_auto_schema( request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'taskname': openapi.Schema(type=openapi.TYPE_STRING, description='Add taskname'), 'completion': openapi.Schema(type=openapi.TYPE_BOOLEAN, description='completion'), } ) ) def post(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') req_data = { "username": User.objects.filter(username=payload['username']).first(), "taskname": request.data['taskname'], "completion": request.data['completion'], } print(5*'*', req_data) serializer = TaskSerializer( data=request.data ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) However, when I create a task I can retrieve the user from the token and I send the post request via swagger to /task, I get … -
Correct way to store JSON into SQL database in React/Python(Django) app
So, I have, in my React application, a method that will generate a json with some settings and data, like this: const generateJSON = async () => { const json = generateManualJSON(caseId); const data = { cdata: customData, settings: json, }; try { const response = await Axios.post(`/manual/${caseId}/generate`, { manual_settings: JSON.stringify(data) }); console.log('response.data', response.data); } catch (error) { setError(arch, true, [error.message]); console.error(error); } }; and this will end up in this View in my Django application: class Manual(APIView): def transaction(self, case_id, action, request): user = request.user manual_settings = request.data['manual_settings'] if (action == 'generate'): CaseAutomationStatusModel.objects.create( current_ind=True, case_id=case_id, created_by=user, modified_by=user, status_comment=manual_wire_settings ) def post(self, request, case_id, action): try: self.transaction(case_id, action, request) return JsonResponse({ 'status': 200, 'message': 'Success' }) except Exception as err: print('*** API error', err) We are using PostgreSQL as database. The purpose of this is that we have a few jobs that run with nextflow and python running in paralel, and it this nextflow job will get this json in the database, and use it. But the problem is, the way it is currently stored, probably due to lack of escape characters, the database string input (which is the one we saved in the react/python project) is breaking up into … -
Chatbot with Knowledge base using GPT 3.5 turbo - Prompt optmizing [closed]
For context, I've been developing a chatbot with Chatgpt in pythom, more precisely, with Django. I am developing a prompt for my chatbot that uses chatgpt and it is giving some problems when I enter a lot of information in it. My goal for this prompt: What I want for my chatbot are short and objective answers, so that they can be as close as possible to a human, without leaving out some information. Problems encountered at the prompt: With my prompt, which I can provide, there are times when the chatbot is able to capture the menu data and there are times when it is not. Also, the chatbot generates some very large responses, passing unnecessary information to customers at that time of the response. The access link for my prompt is: "https://docs.google.com/document/d/1OGAlRGWQbhFbJWKKn5CBXobj3danvVskPsQuZa_CbTk/edit?usp=sharing" What has already been done: What I've been working on for a long time is a prompt for a chatbot that serves customers at a pizzeria. I'm trying to configure the prompt in countless ways but I'm not getting the ideal answers for my business. My prompt already has the menu separated in another context and is called, from the main prompt, through a function. With … -
'django-admin' is not recognized however i installed django
'django-admin' is not recognized as an internal or external command, operable program or batch file. i wrote pip install django and it installed. but when I try this: django-admin --version in cmd it wrote this: 'django-admin' is not recognized as an internal or external command, operable program or batch file. What's the problem?? -
Unable to run Django project with Azure
I have made a website where everything ran on Django. I recently went over to storing data on Azure, but now I am not able to run the server to continue developing. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\db\utils.py", line 113, in load_backend return import_module("%s.base" % backend_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mssql' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File … -
Default value from related model
I have a zipcode table and a persontable. When entering the persons zip I'll need the persons cityfield to be filled with the city from the related ziptable. models.py: from django.db import models class Zip(models.Model): zipcode = models.IntegerField() city = models.CharField(max_length=200) def __str__(self): return str(self.zipcode) class Person(models.Model): name = models.CharField(max_length=200) zipcode = models.ForeignKey('Zip',on_delete=models.CASCADE,related_name="zip_of_this_person") personcity = models.CharField(max_length=200) def __str__(self): return self.name forms.py from django import forms from .models import Zip, Person class ZipForm(forms.ModelForm): class Meta: model = Zip fields = ('zipcode', 'city',) class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'zipcode', 'personcity' ) views.py from django.shortcuts import render, redirect, get_object_or_404 from .forms import PersonForm, ZipForm from .models import Zip, Person # Create your views here. def index(request): return render(request, 'theapp/index.html' ) def person_new(request): if request.method == "POST": form = PersonForm(request.POST) # author_name = '2222'.Zip.city if form.is_valid(): post = form.save(commit=False) post.save() return redirect('person_detail', pk=post.pk) else: form = PersonForm() return render(request, 'theapp/person.html', {'form': form}) def zip_new(request): if request.method == "POST": form = ZipForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('zip_detail', pk=post.pk) else: form = ZipForm() return render(request, 'theapp/zip.html', {'form': form}) def person_detail(request, pk): post = get_object_or_404(Person, pk=pk) weather= "testing purposes" context= { 'post': post, 'weather': weather, } return render(request, 'theapp/person_detail.html', … -
Django signals returns Notification.user must be a "CustomUser" instance
I'm trying to use this method to add a Notifications system to my Django app. I want to notify our users when the Invitation model is created. However, the problem is that the Invitation model does not have a user field, and we don't want to add the user field to the model, because we don't want to make the person who is going to create the Invitation model a user, How can I make the first_name as the one who created the Invitation model, the method I'm using down below return an error: Cannot assign "<Invitation: Adamu>": "Notification.user" must be a "CustomUser" instance. the signals: from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from .models import Level, Notification, Invitation from django.urls import reverse User = settings.AUTH_USER_MODEL @receiver(post_save, sender=Invitation) def comment_post_save(sender, instance, **kwargs): message = f'{instance.first_name} has booked our"{instance.select_type.level} room"' link = reverse('Open-Room', args=[str(instance.select_type.slug)]) notification = Notification(user=instance, message=message, link=link) notification.save() models: class Invitation(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) id_card = models.CharField(max_length=50, choices=ID_CARD) id_number = models.CharField(max_length=100) nationality = models.CharField(max_length=50, choices=LIST_OF_COUNTRY) state = models.CharField(max_length=50) town = models.CharField(max_length=50) address = models.CharField(max_length=90) phone_number = models.IntegerField() guardian_phone_number = models.IntegerField() number_of_day = models.IntegerField() visited_for = models.CharField(max_length=40, choices=VISITED_FOR_THIS) date_created = models.DateTimeField(auto_now_add=True) select_type … -
I wrote a middleware that handles refreshing the access token if expired but it is not properly working, (I use DRF combined with simple jwt )
from datetime import datetime, timezone from rest_framework_simplejwt.tokens import RefreshToken from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin class TokenRefreshMiddleware(MiddlewareMixin): def process_response(self, request, response): if response.status_code == 200: refresh_token = request.COOKIES.get('refresh_token') if refresh_token: try: decoded = RefreshToken(refresh_token, verify=False) if decoded: if decoded.access_token['exp'] < datetime.datetime.now(timezone.utc).timestamp(): refresh = RefreshToken(refresh_token) response.set_cookie('access_token', refresh.access_token) response.set_cookie('refresh_token', refresh) except: pass if response.status_code == 401: refresh_token = request.COOKIES.get('refresh_token') if refresh_token: print ("refresh_token = = = = = ", refresh_token) try: decoded = RefreshToken(refresh_token, verify=False) if decoded: refresh = RefreshToken(refresh_token) response.set_cookie('access_token', refresh.access_token) response.set_cookie('refresh_token', refresh) response.status_code = 200 except: pass return response hello I m working on the authentication using django (dj-rest-auth), I use httpOnly cookie to store the access token and refresh token so I don't have access to them in the front end, which means I must handle that in the backend, I wrote this middleware to keep refreshing the access token but whenever it is expired I get the response below: { "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" } ] } until I reload the page for the second time then the authenticated user shows up -
I'm getting value error while redirecting checkout page in django
error enter image description here my checkout.html enter image description here my payment_done view enter image description here checkout.html is supposed to redirect on orders page after successful payment, but when the payment gets done it gets redirected to this error instead of orders page, i've tried everything from changing the type of cust_id to int, please help me solve this asap this is the github repo link of the code -
Django custom lookup, error on using modulus operation in as_sql()
from django.db.models import Lookup class NotEqual(Lookup): lookup_name = 'div' def as_sql(self, compiler, connection): lhs, lhs_param = self.process_lhs(compiler, connection) rhs, rhs_param = self.process_rhs(compiler, connection) params = lhs_param + rhs_param return "%s %% %s == 0" % (lhs, rhs), params i am using Book.objects.filter(rating__div=5) Error . . . File "D:\PROJECTS\Projects_Personal\django_challenges_venv_\Lib\site-packages\MySQLdb\cursors.py", line 200, in _mogrify query = query % args ~~~~~~^~~~~~ ValueError: unsupported format character '%' (0x25) at index 272 this only happening with modulus operation with % operator, i can use MOD etc. but i wanted to know why with this operator this error happening. i tried to change this operator to other, they work fine but i didn't get anything for this not even in docs -
Django integrity error on parallel requests
I have: IntegrityError duplicate key value violates unique constraint "user_pkey" DETAIL: Key (id)=(3220037) already exists. This happens in this part of the code user = User() user.save() Model is pretty simple, 3 fields. So it happens when there are lot's of parallel requests to my endpoint. I thought Django deals with race condition under the hood in such an easy operation. Database is Postgres, default transaction isolation is read commited. Maybe smth changed with newer Django versions? Do I have to handle race condition by myself in code? -
Problem for import cloudgenix lib in views file on Django
Good morning, As said in the title, I am facing a problem when want to import cloudgenix library into view file using Django framework. from django.shortcuts import render import cloudgenix My error : "Unable to resolve 'cloudgenix' importPylance reportMissingImports" I hope someone can help me I uninstall/install the library and i try to import on other files like models file -
Sync local postgres database with server postgres database?
Currently, I have a PostgreSQL database running on my local server, and everything is functioning well. Now, I want to synchronize this local database with another database on a remote server but only in a specific schema. There are two scenarios to consider: Case I: When an internet connection is available, I need the synchronization to occur immediately between the local and remote databases. Case II: In the absence of an internet connection, I want to store all changes in the local server. Once the internet connection becomes available, the system should automatically transfer all the unsynchronized data from the local server to the remote server. I need guidance on the best approach to achieve this synchronization considering both cases.