Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
antd Global color setting
I am new to antd and need to set the global theme to one of the antd colour palettes. I am building an app using Django, React and antd. I have installed the colours package: npm install @ant-design/colors --save Then I added the palette to my Layout.js file, my default layout: import { purple } from '@ant-design/colors'; Which shows up in the console console.log(purple); console.log(purple.primary); I am struggling with how to make this override the default colours and display the purple ones. I have tried to include in the theme: const theme = { primary: purple[5] }; I have also tried to add to the token: const { token: { purple, colorBgContainer, borderRadiusLG }, } = theme.useToken(); -
Unable to migrate in Second Multi database in Django
I have implemented multi-DB concept inside my Django project where for whole project i am using default db and for User I am using separate DB here are the settings.py file configs: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': default_db, 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), }, 'auth_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'user_auth_db', 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), }, } # ADDING ROUTE TO SPECIFY DB ROUTING SPECIFIC user RELATED CHANGES TO REFLECT Into auth_db database not inside default db DATABASE_ROUTERS = ["main_Project_directory.db_routers.UserAuthRouter"] Now this is the db_routers.py file class UserAuthRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {"auth_user", 'contenttypes'} # Apps to be include inside auth_db def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return "auth_db" return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return "auth_db" return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label … -
In Django the error is, TypeError at /Hod/Student/Add 'Course' object is not iterable
(https://i.stack.imgur.com/1qBDd.png) Even if I change the course = Course.objects.get(id = course_id) to course = Course.objects.filter(id = course_id) there seems no error thrown but the message does not get printed that 'Student added successfully'. **Hod_views.py** Even if I change the course = Course.objects.get(id = course_id) to course = Course.objects.filter(id = course_id) there seems no error thrown but the message does not get printed that 'Student added successfully'. from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from app.models import Course, Session_Year, CustomUser, Student from django.contrib import messages @login_required(login_url="/") def HOME(request): return render(request, "Hod/home.html") @login_required(login_url="/") def ADD_STUDENT(request): course = Course.objects.all() session_year = Session_Year.objects.all() if request.method == "POST": profile_pic = request.FILES.get('profile_pic') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') address = request.POST.get('address') gender = request.POST.get('gender') course_id = request.POST.get('course_id') session_year_id = request.POST.get('session_year_id') if CustomUser.objects.filter(email=email).exists(): messages.warning(request, "Email Is Already Taken!") return redirect('add_student') if CustomUser.objects.filter(username=username).exists(): messages.warning(request, "Username Is Already Taken!") return redirect('add_student') else: user = CustomUser( first_name = first_name, last_name = last_name, username = username, email = email, profile_pic = profile_pic, user_type = 3 ) user.set_password = password user.save() course = Course.objects.get(id = course_id) session_year = Session_Year.objects.get(id = session_year_id) student = Student( admin = user, address = address, session_year_id … -
I am facing problem in connection pgbouncer with postgresql in django
for the configuration of pgbouncer with postgresql in pgbouncer.ini file i have done mydb= dbname=mydb host=**.**.**.** port=5432 listen_addr = * listen_port = 6432 unix_socket_dir = /var/run/postgresql then in userlist.txt file i have "usr" "pass" then in django settings.py `DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', #its db name 'USER':'usr', #it's my user name of database 'PASSWORD': 'pass', #it's my password of database 'HOST': 'localhost', #it's my host of database } }` but when i started gunicorn server then in status it is giving me an error that Mar 20 07:35:27 testenv gunicorn[288076]: FATAL: password authentication failed for user "usr" I tried to configure pgbouncer with postgresql to solve the problem of max_connection_pooling but it is constantly giving the same error when i'm tried to start the gunicorn server. I'm expecting to solve django.db.utils.OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections -
I want to update the price for a product on Stripe
When a subscription plan is created in DB, it is synced to create a corresponding product and price on stripe. However, now i want to change the price of a plan. How would I go about changing it on stripe? I have read that we can create a new price and make the old one inactive, but how would we link the new price to the product? And what about existing users? Is it easier done using the dashboard? -
Django, Docker, SlickGrid - Can't walk dependency graph: Cannot find module 'slickgrid'
I'm trying to build Django backend based application on Docker using PyCharm with NPM and slickgrid. When in some .js file trying to import slickgrid: import { SlickGrid, SlickDataView } from 'slickgrid'; I'm getting Django error: FilterError at /todo/ Error: Can't walk dependency graph: Cannot find module 'slickgrid' from '/opt/project/eTools/todo/static/todo/js/main.js' For dealing with Django static assets I use: django-compressor django-compressor-toolkit In Dockerfile I have something like: ` Set work directory WORKDIR /code (...) RUN apt-get install -y nodejs npm (...) #Slickgrid RUN npm install -g browserify babelify@8 babel-core babel-preset-env babel-cli babel-preset-es2015 RUN npm install -g slickgrid (...) Copy the Django project COPY ./eTools/ /code/ ` It looks like npm used indirectly by Django does not see 'slickgrid'. In bash for Docker I see following: a) in location where app was copied in last step of Dockerfile (/code/ location) npm has slickgrid: root@f7401a6daac5:/code# npm list slickgrid code@ /code └── slickgrid@5.8.2 b) but for unknown reason (for me at least ;)) npm seems to be called from location from exception ('/opt/project/'). checked in docker bash and there is no 'slickgrid': root@f7401a6daac5:/opt/project# npm list slickgrid eTools_root@1.0.0 /opt/project └── (empty) Could you please advice how I can fix this issue? And why code is … -
Flask TypeError: __init__() got an unexpected keyword argument 'as_tuple'
While I am testing my API I recently started to get the error below. if request is None: > builder = EnvironBuilder(*args, **kwargs) E TypeError: EnvironBuilder.__init__() got an unexpected keyword argument 'as_tuple' Code: @pytest.fixture(autouse=True) def client(): app = my_app() with app.test_client() as client: yield client def test_new_func(client, monkeypatch): monkeypatch.setattr(UnitPricing, 'find_unit_price', find_unit_pricing) monkeypatch.setattr(FullPricing, 'find_full_price', find_full_pricing) response = client.post("/price/calc", json=input_payload) assert response.status_code == 200 assert json.loads(response.data) == output_data In one of the solutions, it was suggested to pin werkzeug version to 2.0.3 and my requirement.txt file is meeting this condition but I'm still getting the error. TypeError: __init__() got an unexpected keyword argument 'as_tuple' Any help would be appreciated. -
Django unit test returning empty response for method of class
I am testing a class that connects to the database, and does some other stuff. Right now I am testing the returned value from a method. But it is returning empty list. class BaseAPISyncTestCase(unittest.TestCase): # overriding variables that are required by the test class @override_settings(DAILY_SYNC_BASE_URL='') @override_settings(DAILY_SYNC_SECRET_APP_KEY='') @override_settings(DAILY_SYNC_APP_NAME='') def test_retrieve_data_success(self): """Tests successful retrieval of data, validation, and sync history creation.""" mock_response = [ {'Id': 1, 'SyncDate': '2024-03-20', 'SyncType': 'UPDATE'}, {'Id': 2, 'SyncDate': '2024-03-20', 'SyncType': 'INSERT'}, ] with patch.object(BaseAPISync, 'retrieve_data', return_value=mock_response) as mock_retrieve_data: class TestSync(BaseAPISync): serializer_class = Mock() serializer_class.return_value.is_valid.return_value = True endpoint_key = 'test_endpoint' sync_category = 'Test Category' bulk_create_records = Mock() bulk_update_records = Mock() prepare_data_to_save = Mock() updatable_fields = Mock() sync = TestSync() sync.retrieve_data() self.assertEqual(mock_retrieve_data.call_count, 1) self.assertEqual(sync.last_retrieved_record, 2) # Last record ID self.assertEqual(len(sync.sync_context['validated_data']), 2) self.assertEqual(len(sync.sync_context['sync_history_dict']), 2) How can I debug this code, the retrive_data method is not being called because I checked by writing print statement. -
citus add node --> "fe_sendauth: no password supplied" error
I am trying to setup multi node schema based sharding for postgresql database using citus extension. I have two azure virtual machines , one is working as worker node('20.40.43.246') and other as coordinator ('20.198.17.232') I am following this documention https://docs.citusdata.com/en/stable/installation/multi_node_debian.html#steps-to-be-executed-on-all-nodes On worker node database is set up and it is running fine. on coordiator node when i run sudo -i -u postgres psql -c "SELECT * from citus_add_node('20.40.43.246', 5432);" I am getting below error. ERROR: connection to the remote node 20.40.43.246:5432 failed with the following error: fe_sendauth: no password supplied What configuration do i need to change in pb_hba.conf on worker node? -
Django Channels WebSocket Authentication with React: Stuck at Handshake
I'm integrating Django Channels WebSockets into my React app and hit a roadblock with user authentication during the WebSocket handshake. Despite setting up everything according to the docs, my WebSocket connection doesn't recognize authenticated users. Here’s what my setup looks like: Django Channels (consumers.py): from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() React (Chat.js): import React, { useEffect } from 'react'; import { w3cwebsocket as W3CWebSocket } from "websocket"; const client = new W3CWebSocket('ws://127.0.0.1:8000/ws/chat/room_name/'); const Chat = () => { useEffect(() => { client.onopen = () => { console.log('WebSocket Client Connected'); }; client.onmessage = (message) => { console.log(message); }; }, []); return <div>Chat Component</div>; }; export default Chat; I’m passing the session ID/token via the WebSocket URL, but Django doesn't authenticate the user on the WebSocket connection. I’m missing the part where I can authenticate the WebSocket request in Django Channels based on the session ID or token provided by the React app. Has anyone faced a similar issue, or does anyone know what I might need to do differently here? Any help or guidance would be greatly … -
Can I use django RQ to delay execution of tasks like saving models to the database? When I try It causes weird issues
I have the following code: @job def create_model(): test_text = "Text1" TestModel.objects.create(test_text=test_text) print("Done!") def test_view(request): create_model.delay() return HttpResponse("Ok!") But this produces weird errors in console: (venv) ➜ DjangoRedisQueueTest python manage.py rqworker 08:58:01 Worker rq:worker:e95d3ce3ab82415cb5f9b1eb8dbdad72 started with PID 30490, version 1.16.1 08:58:01 Subscribing to channel rq:pubsub:e95d3ce3ab82415cb5f9b1eb8dbdad72 08:58:01 *** Listening on default... 08:58:01 Cleaning registries for queue: default 08:58:04 default: drq_test.views.create_model() (f3701c9e-63df-42aa-9dd6-5169892c644c) objc[30495]: +[__NSCFConstantString initialize] may have been in progress in another thread when fork() was called. objc[30495]: +[__NSCFConstantString initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug. 08:58:04 Moving job to FailedJobRegistry (Work-horse terminated unexpectedly; waitpid returned 6 (signal 6); ) How can I use django RQ to delay such tasks like saving models to the database -
my project name as changed as cannot changed back on pycharm
I've created a project called Socialmedia, few days ago suddenly i noticed the name of the project as changed to a file inside the project as you can see, the project name is manage.py on not Socialmedia the main dir I've tried: Resetting to default IDE and opening the dir project Socialmedia Changing the name Opening the project as Socialmedia -
spoonacular API and django
i have a question. Can i add spoonacular API to my django project? I'm doing a recipe-sharing project and would really like to have a database with ingridients, so i can choose them when making new recipe. My question is if i can have like 2 databases, if that makes sense? i would have djangos database db.sqlite3 and this spoonacular API. Thanks I looked at some youtube tutorial, but it doesnt make sense for me. I tried google it, but unfortunately didnt really catch anything. -
How can I ensure synchronized incrementation of two counters in a Celery async task
I'm encountering a scenario where a single endpoint is receiving multiple concurrent requests for image uploads. Upon successful upload, two counters need to be incremented synchronously. Initially, I tried synchronously incrementing the counters, but due to race conditions, the results were incorrect. Consequently, I implemented an asynchronous Celery task to handle this. However, while one counter stays in sync, the other does not. I'm puzzled why only one counter is affected if both are subjected to the same conditions. I am using Postgres as my database. To address the issue of asynchronous counter incrementation, one potential solution is to remove the counters altogether and instead track the number of uploaded images. However, it's crucial to understand the root cause of the asynchronous behavior to prevent similar issues in the future. This is the piece of code that is doing the increment @shared_task def increment_album_and_event_image_count(album_id): try: with transaction.atomic(): album = Album.objects.get(id=album_id) album.image_count_in_album = F("image_count_in_album") + 1 album.save() album.event.number_of_images_across_albums = ( F("number_of_images_across_albums") + 1 ) album.event.save() return True except Exception as e: logger.error(f"Error incrementing image count: {e}, album: {album}") return False Here the number_of_images_across_albums has correct information while image_count_in_album does not. Here are the model details: class Album(TimeStampedModel): image_count_in_album = models.IntegerField(default=0) event … -
Understanding keycloak authentication with mozilla-django-oidc
I am currently trying to use Keycloak with Django. I use the mozilla-django-oidc package for this and have used this tutorial as a guide, but with my own Keycloak server. So far, everything is working fine. The protected view can only be accessed after logging in via Keycloak. However, django rest framework is causing me problems. I have made the configuration as described in the instructions, but I always get 401 (Unauthorized) back for requests to the Django Rest Framework endpoint. And I don't understand why. As far as I understand it, mozilla-django-oidc sets a "sessionid" cookie to authenticate the user. I can also access the protected view. For a request to the Django Rest Framework endpoint, however, I have to send an Authorization header with the access token according to the mozilla-django-oidc documentation. But where do I get this access token in my single page application to set it in the Authorization header? I have tried to read the access token in the SPA from the mentioned "sessionid" cookie. But this cookie is http only. -
Filling the FormMixin form
Is it possible to populate FormMixin form data without passing the form variable to the template? I have a template, but I don't understand how to create a form with Django, so I just specify the name attribute in the template. The form is created, everything is fine, I override the method get_initial() method, but the form is not filled out Is it possible to do this or do I need to pass the form variable? class CommentEditView(View, FormMixin): form_class = EditCommentForm def get_initial(self): initial = super().get_initial() comment = get_object_or_404(Comment, pk=15) initial['review_text'] = comment.review_text initial['grade'] = comment.grade return initial def get(self, request, comment_id): return render(request, 'catalog/review-edit.html') class EditCommentForm(ModelForm): class Meta: model = Comment fields = ['review_text', 'grade'] <form method="POST"> {% csrf_token %} <textarea class="product-detail-reviews-textarea" name="review_text" id="id_review_text"></textarea> {% for error in form.review_text.errors %} <p class="product-detail-reviews-error">* {{ error }} </p> {% endfor %} <div class="product-detail-reviews-row"> <div class="product-detail-reviews-stars"> <p>Stars:</p> <div class="rating-area"> <input type="radio" id="id_grade_five" name="grade" value="5"> <label for="id_grade_five" title="Star «5»"></label> <input type="radio" id="id_grade_four" name="grade" value="4"> <label for="id_grade_four" title="Star «4»"></label> <input type="radio" id="id_grade_three" name="grade" value="3"> <label for="id_grade_three" title="Star «3»"></label> <input type="radio" id="id_grade_two" name="grade" value="2"> <label for="id_grade_two" title="Star «2»"></label> <input type="radio" id="id_grade_one" name="grade" value="1"> <label for="id_grade_one" title="Star «1»"></label> </div> </div> <button type="submit" class="product-detail-reviews-link">Confirm</a> </div> {% … -
My formset is not valid and i cannot retreive the cleaned_data of each form
I have 3 models below class MenuItem(TranslatableModel): item_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) categories = models.ManyToManyField(MenuCategory, related_name='menu_items') translations = TranslatedFields( name=models.CharField(_('name'), max_length=200), slug=models.SlugField(blank=True, null=True, unique=True), description=models.TextField(_('description'), blank=True, null=True) ) price = models.DecimalField(_('price'), max_digits=10, decimal_places=2, default=0) image = models.ImageField(_('image'), upload_to='menu_items/%Y/%m/%d', blank=True, null=True) is_available = models.BooleanField(_('is available'), default=True) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) def __str__(self): return f'{self.name}'.title() def get_absolute_url(self): return reverse('menu_management:item_detail', args=[self.item_id, self.slug]) class MenuOptionGroup(TranslatableModel): group_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name='options_groups') translations = TranslatedFields( name=models.CharField(_('name'), max_length=200), slug=models.SlugField(blank=True, null=True, unique=True) ) is_required = models.BooleanField(_('is required'), default=False) max_choices = models.IntegerField(_('max choices'), blank=True, null=True) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) def __str__(self): return f'{self.name}'.title() class MenuOption(TranslatableModel): option_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) group = models.ForeignKey(MenuOptionGroup, on_delete=models.CASCADE, related_name='options') translations = TranslatedFields( name=models.CharField(_('name'), max_length=200), slug=models.SlugField(blank=True, null=True, unique=True) ) image = models.ImageField(_('image'), upload_to='menu_options/%Y/%m/%d', blank=True, null=True) price_change = models.DecimalField(_('price change'), max_digits=10, decimal_places=2, default=0) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) def __str__(self): return f'{self.name}'.title() From this 3 class I am trying to create a formset that will go through the MenuOptionGroup and pick up their repective menu_option. my form look like the below class MenuOptionGroupForm(TranslatableModelForm): menu_option = forms.ModelChoiceField(queryset=MenuOption.objects.none(), empty_label="No options", required=False) class Meta: model = MenuOptionGroup # Include the fields that … -
Failed to fetch: Js code on Html template
In a JS code I'm using fetch to make GET requests to a url to obtain data in JSON format. The js code is located in my Django project and I use it in some templates. When I click on the button that activates the js script, it tells me that there is an error in the fetch, can someone help me? I have tried to solve it by allowing cross origin but nothing. -
cant link css file to html file with
i cant link a css file to an html file im am using visual studio code and python django to do this my files are like this project |templates | home.html | style.css app.py home.html <!DOCTYPE html> <html> <head> <link href='https://fonts.googleapis.com/css?family=Raleway:400, 600' rel='stylesheet' type='text/css'> <link href='assets/style.css' rel='stylesheet' type='text/css'/> </head> <body> ... </body> style.css html, body { margin: 0; padding: 0; } header { background-color: #333333; position: fixed; width: 100%; z-index: 5; } h1 { font-family: 'Times New Roman', Times, serif; color:cadetblue } app.py from flask import Flask, render_template app = Flask(__name__, template_folder="templates") @app.route("/home") @app.route("/") def index(): return render_template("home.html") i tried using the templates folder, it didnt work i tried without using the templates folder, it didnt work it doesnt raise any error but the page just doesnt has the css style, for example the h1 tags keep being black with the default font, and they shoud be blue with Times New Roman Font Any help would be appreciated 🙂 -
Runs on Local Host but not on heroku
I keep getting this Server 500 error while deploying my to Heroku. It runs perfectly on my Local host. The other page on the site works fine but this one has the News-API. Not sure what to do next. Debug ERROR \`KeyError at / 'articles' Request Method: GET Request URL: https://lvl27-9617c0ce663b.herokuapp.com/ Django Version: 4.2.10 Exception Type: KeyError Exception Value: 'articles' Exception Location: /app/news/views.py, line 13, in index Raised during: news.views.index Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.18 Python Path: \['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'\] Server time: Tue, 19 Mar 2024 23:03:02 +0000 Traceback Switch to copy-and-paste view /app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py, line 55, in inner response = get_response(request) … Local vars /app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py, line 197, in \_get_response response = wrapped_callback(request, \*callback_args, \*\*callback_kwargs) … Local vars /app/news/views.py, line 13, in index a = gaming_news\['articles'\]\` CODE from django.shortcuts import render import requests import os from dotenv import load_dotenv, dotenv_values from newsapi import NewsApiClient load_dotenv() API = os.getenv('NEWS_API') def index(request): url = (f"https://newsapi.org/v2/everything?q=gaming&apiKey={API}") gaming_news = requests.get(url).json() a = gaming_news['articles'] urlToImage = [] author = [] title = [] description = [] url = [] for i in range(len(a)): f = a[i] urlToImage.append(f['urlToImage']) author.append(f['author']) title.append(f['title']) description.append(f['description']) url.append(f['url']) news_list = zip(urlToImage, author, title, description, url) context = {'news_list': news_list} … -
Convert XPS To PDF with Python
I have a Django project. There is a need to convert XPS format to PDF. The PDF file itself can be obtained as a byte array upon request from another system. Perhaps there is some library or working implementation in Python? doc_data = get_PDF_file_in_pilot(project=project, file_id=id) if doc_data.get("error"): return HttpResponse(json.dumps(doc_data), content_type="application/json", status=500) file_name = doc_data["file_name"] file_name_no_extension, file_extension = os.path.splitext(file_name) if doc_data.get("file_name") and doc_data.get("file_content"): file_content = doc_data["file_content"] file_data = { 'status': 'success', 'file': base64.b64encode(file_content).decode('utf-8'), 'file_name': file_name } return JsonResponse(file_data) -
How do I implement forms for user input to register and login in Django when I already have the views using JWT?
I´m learning how to work with JWT(pyJWT) in Django, in this case I´m trying to authenticate users with it, I followed a tutorial and using postman it worked, I use mysql and the passwords were hashed and the tokens were generated succesfully, now the only thing left is to create the forms so the user can input his credentials but I don´t know how to do proceed. Views.py class RegisterView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found') if not user.check_password(password): raise AuthenticationFailed('Incorrect password') payload = { 'id': user.id, 'exp': datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=60), 'iat': datetime.datetime.now(datetime.timezone.utc) } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = {"jwt": token } return response class UserView(APIView): def get(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unathenticated!') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Uathenticated') user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) class LogoutView(APIView): def post(self, request): response = Response() response.delete_cookie('jwt') response.data = { 'message': 'Success' } return response Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'email', 'password', 'first_name', … -
Django views.py Lookup value from constant list
In a django views.py how do you take a selection (number) from input can get the matching "Description"? For example the user selects 3 and returns "Yellow" colors = [ ('0','black'), ('1','white'), ('2','Red'), ('3','Yellow'), ('4','Blue'), ('5','Green') ] ... colorSelection = form.cleaned_data.get('color') #lookup color description colorDescription = ??? -
Hashing the password if it is not hashed in django
When I try to create a password for the user using the admin interface is doesn't get hashed. So I added this line in the user model def save(self, *args, **kwargs): self.set_password(self.password) While this solves the issue. while creating user using createsuperuser it saves the password as a hash But when I try to login into the admin interface is says incorrect password. I'm sure it's caused by the adding the above line into the code. When i remove the line, createsuperuser works fine but password isn't hashed in the admin interface, when i add the line admin works while createsuperuser doesn't. I want to hash the password if it isn't hashed yet. -
Getting "django.db.utils.ProgrammingError: column "v11.confirmed" must appear in the GROUP BY clause
I am getting "django.db.utils.ProgrammingError: column "v11.confirmed" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...'xandr']::varchar(254)[] AND (V11."id" IS NULL OR V11."confi...".Anyone please suggest what's wrong with the query?thank you in advance data = AdidMeta.objects.filter(id__in=adid_meta_file_list.values_list('adid_meta_id', flat=True)).prefetch_related( "adidmetafileupload_set__creativeencoding_set", "adidmetafileupload_set__creativeacknowledgement_set", "xandrcreative_set", "assets_set__ad_copy_rotation" ).annotate( operators=ArrayAgg("distributors__name", ordering="distributors__name", distinct=True), no_operator=Case( When(Q(operators=[None]) & Q(adidmetafileupload__creativeacknowledgement__isnull=False, adidmetafileupload__creativeacknowledgement__is_received=True, adidmetafileupload__creativeencoding__isnull=False, adidmetafileupload__creativeencoding__is_encoded=True ) & Q( Q(orderline__isnull=False, orderline__status=OrderLine.ACTIVE) | Q(orderline__isnull=True, assets__ad_copy_rotation__orderline__status=OrderLine.ACTIVE) ), then=Value(1) ), default=Value(0), output_field=IntegerField() ), only_dish=Case( When(Q(operators=[OPERATOR_NAME.DISH]) & Q(adidmetafileupload__creativeacknowledgement__isnull=False, adidmetafileupload__creativeacknowledgement__is_received=True, adidmetafileupload__creativeencoding__isnull=False, adidmetafileupload__creativeencoding__is_encoded=True ), then=Value(1) ), default=Value(0), output_field=IntegerField() ), only_directv=Case( When(Q(operators=[OPERATOR_NAME.XANDR]) & Q(xandrcreative__isnull=False, xandrcreative__confirmed=True), then=Value(1) ), default=Value(0), output_field=IntegerField() ), both_dish_directv=Case( When(Q(operators=[OPERATOR_NAME.DISH, OPERATOR_NAME.XANDR]) & Q(adidmetafileupload__creativeacknowledgement__isnull=False, adidmetafileupload__creativeacknowledgement__is_received=True, adidmetafileupload__creativeencoding__isnull=False, adidmetafileupload__creativeencoding__is_encoded=True, xandrcreative__isnull=False, xandrcreative__confirmed=True ), then=Value(1) ), default=Value(0), output_field=IntegerField() ) ).distinct().filter( Q(no_operator=1) | Q(only_dish=1) | Q(only_directv=1) | Q(both_dish_directv=1) ) Tried multiple way but could not resolved the error.