Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get user details after authenticate method
after doing: user = authenticate(username=username, password=password) if user is not None: print(user.first_name) basically I want to to get basic details of the just authenticated user mainly first_name. -
Django checking if message.tags contains string always return false
I have set extra_tags in my view, but when I check for the target tag in my template, the condition always evaluates to false. View: messages.success(request, "success") messages.info(request, "you can undo this", extra_tags="undo") Template: {% for message in messages %} {{ message.extra_tags }} <li> {% if 'undo' in messages.extra_tags %} this has undo in tags {% else %} {{ message }} {% endif %} </li> {% endfor %} This result in this HTML: * success * you can undo this This is what I expect * success * this has undo in tags (1) I have confirmed that the "undo" tag is output from {{ message.extra_tags }} (2) I have tried messages.tags instead of messages.extra_tags but neither method reaches the true branch in the if condition. -
Django rest framework password reset knox Authentication
I am trying to reset password in django rest framework using knox authentication I didn't find anything -
Django .first() method cuts first digit from a Decimal
I am seeing really strange behavior when using .first() method on a QuerySet. After calling the method, first digit from a Decimal value gets cut. Code: def _get_month_value(self, id: int, month_values: QuerySet) -> int: print("----------") print(month_values) print(month_values.filter(id=id).values('tsum')) print(month_values.filter(id=id).values('tsum').first()) print(month_values.filter(id=id).values('tsum')[0]) The outputs are as follows: <QuerySet [{'id': 1, 'tsum': Decimal('519')}, {'id': 3, 'tsum': Decimal('1019')}, {'id': 5, 'tsum': Decimal('0')}, {'id': 9, 'tsum': Decimal('0')}]> <QuerySet [{'tsum': Decimal('519')}]> {'tsum': Decimal('19')} {'tsum': Decimal('519')} As you can see for id 1 the original value is 519 but after I call the first() method it gets turned into a 19. This does not happend if I manually call the first item in QueySet using [0]. Any idea what might be causing this issue? Thanks in advance :) -
Django how to use DateTimeField without microseconds?
My field in model: created_at = models.DateTimeField(auto_now_add=True) it returns: "created_at": "2023-02-21T09:24:55.814000Z" how can i get this one (without last part): "created_at": "2023-02-21T09:24:55" Is there another way instead of this? representation['created_at'] = instance.created_at.split('.')[0] -
Add a field to a model in Django without having to delete the database
I would like to add a field to a model in Django. However, when I do this I get the following error: django.db.utils.OperationalError: no such column: . I know I can fix this by deleting the database and running migrations, but is there a way to do it without having to delete the database? It is a lot of work to put all the data in there again every time I want to add a field to a model. Running migrations and deleting the migration files does not work. -
I don't know, how to create Apache handlers and connect to Django project
I built eCommerce site in Django REST Framework. I deployed to cPanel hostinger. Please show me how to connect Apache to project. enter image description here Apache page -
upload excel to create bulk database row in django rest framework
Hey developer's I am stuck to create bulk database entity using excel file upload by Django rest framework help me to upload excel and create row in Database. class DispatchAdvice(models.Model): da_id = models.AutoField(primary_key=True, unique=True) jobcode_da_no = models.CharField(max_length=100, null=True) da_to = models.CharField(max_length=1150, null=True) da_cc = models.CharField(max_length=1150, null=True) and another database is....... class PanelWise(models.Model): id = models.AutoField(primary_key=True, unique=True) da_id = models.ForeignKey(DispatchAdvice, null=True, on_delete=models.CASCADE) panel_name = models.CharField(max_length=150, null=True) section = models.CharField(max_length=150, null=True) item_desc = models.CharField(max_length=700, null=True) make = models.CharField(max_length=100, null=True) model = models.CharField(max_length=100, null=True) qty = models.IntegerField(null=True) zdl_qty = models.IntegerField(null=True) uom = models.CharField(max_length=100, null=True) remark = models.CharField(max_length=100, null=True) and here is file in excel......text Help me for that Create a bulk data table using excel upload -
Django raw sql problems with complex query
I have following query: keyWordsAllStr = ", ".join(keyWordsAll) main_query = Transactions.objects.raw( ''' with cte0 as ( select split_part(analytics_debet, ',', 1) as name from orm_analytics_transactions where account_debet like '103%%' and account_credit not like '10%%' and analytics_debet not in ( %(keyWordsAllStr)s ) and period >= %(min_date)s and period <= %(max_date)s and project_id = %(project_id)s group by analytics_debet order by sum(value_debet) DESC limit 7 ), cte05 as ( select case when split_part(analytics_debet, ',', 1) not in (select name from cte0) then 'Other' else split_part(analytics_debet, ',', 1) end as name from orm_analytics_transactions where account_debet like '103%' and account_credit not like '10%' and analytics_debet not in ( %(keyWordsAllStr)s ) and period >= %(min_date)s and period <= %(max_date)s and project_id = %(project_id)s ), cte1 as ( select d.dt as date, c.name from ( select dt::date from generate_series('2022-03-01', '2023-02-01', '1 month'::interval) dt ) d cross join ( select distinct name from cte05 ) c ), cte2 as ( select split_part(analytics_debet, ',', 1) as name, date_trunc('month', period)::date, sum(value_debet) from orm_analytics_transactions where account_debet like '103%%' and account_credit not like '10%%' and analytics_debet not in ( %(keyWordsAllStr)s ) and period >= %(min_date)s and period <= %(max_date)s and project_id = %(project_id)s group by 1,2 ) select c1.date, c1.name, coalesce(c2.sum, 0) as … -
How to pass exception on frontend side in python django
I've written some code in views.py and .html file. first user has to upload a file in first .html file and in second .html file user can see whether file output is getting or some error occured. After uploading file, another .py file (means fleet_processing.py) runs, that process some calculation of the output in backend. if some exception occured in processing the calculation then I've to pass that exception to user in second .html file, so user can also know what exactly the error is. view.py for second .html file: def fleet_directory(request): country_access = request.session.get("country_access") context = {} fleetDicrectory = FleetPlan.objects.filter(country__in=country_access).all().order_by("-uploaded_at") context["resp"] = fleetDicrectory return render(request, 'fleet_plan/fleet_directory.html', context=context) fleet_processing.py def historicQuanitity(uploadedFileUrl, uid, file_country, useremail, kwargs): try: # code for filteration on file try: # code for calculation on file except Exception as E: print("Error in Query:", E) raise Exception(Exception) from E except Exception as E: print("Error in main:", E) raise Exception(Exception) from E So I want pass the exception in second .html file which happening in the fleet_processing.py file . How can I pass the Exception that coming from the 3rd .py (means fleet_processing.py) file? -
in postman getting error "detail": "JSON parse error - Expecting value: line 3 column 14 (char 18)"
This is my views.py script and i am trying to access the data through postman. the body i am using in postman is: {"query_text": "finance","hasquotes": "False","page": "1","object_return": "12","asset_type": "Documents","sort_by": "date","sort_order":"descending"} but i am getting error: "detail": "JSON parse error - Expecting value: line 3 column 14 (char 18)". Can anyone help? from django.shortcuts import render import time # Create your views here. from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from smart_search_APP.portal_search import * from django.http import JsonResponse from rest_framework.decorators import api_view, authentication_classes from smart_search_APP.auth import CustomAuthentication import gc @api_view(['POST', 'GET']) @authentication_classes((CustomAuthentication,)) def search_funcationality(request): if request.method == 'GET': return JsonResponse({"WARNING": "GET method is not allowed for this API"},safe=False) else: gc.collect() s0 = time.time() q1 = request.data.get('query_text',"") q2 = request.data.get('asset_type',"") q3 = request.data.get('Accelerator_filter',"") q4= request.data.get('DocumentAssetType',"") q5 = request.data.get('Industry_filter',"") q6 = request.data.get('Function',"") q7 = request.data.get('Technology',"") q8 = request.data.get('Format',"") q9 = request.data.get('Geography',"") page = request.data.get('page',0) num_of_obj= request.data.get('object_return',6) sort_by= request.data.get('sort_by',"") sort_order= request.data.get('sort_order',"") hasquote= request.data.get('hasquotes','False') # hasquote="False" if hasquote=='False': query=" ".join([w.lower() for w in q1.split() if not w.lower() in stop_words]) else: query, n = re.subn('[_|-]', ' ', q1) print("query in views.py",query) if q1!="": if len(query)>0: if q2!="" and q3=="" and q4=="" and q5=="" and q6=="" and q7=="" and q8=="" and q9=="": if q2 == 'Documents': documents_result, len_of_documents_result, … -
Python Plotly - restyle pie with buttons
I'm trying to restyle a plotly pie (labels, marker, values), configured via python django. But I'm unable to do it properly - the values are not taken by the pie. I expect to update the pie by new values (example below as same values), new colors and labels in the legend. But it behaves like the pie is disappearing or all values are set to 0. I already had a look into the live generated javascript code and compared it to the examples delivered by plotly but i have not seen any differences. My code is currently: layout = go.Layout( paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color="white", legend=dict( orientation="v", yanchor="bottom", y=0.05, xanchor="left", x=1.05, traceorder='reversed' ), height=300, margin=dict(l=2, r=2, t=1, b=1), ) ... fig = go.Figure(go.Pie(labels=list(firstLabels), values=list(firstValues), marker=dict(colors=color_list), sort=False), layout) fig.update_traces(textposition='inside',textinfo='value') fig.update_layout(uniformtext_minsize=12, uniformtext_mode='hide') button_layer_1_height = 1.08 fig.update_layout( updatemenus=[ dict( buttons=list([ dict( args=[{'labels': ['test1'], 'marker': dict(colors=colorlist_all[1]), 'values': [24] }], label=list(pie_dict.keys())[1], method="restyle" ), dict( args=[{ 'labels': ['test2'], 'marker': dict(colors=colorlist_all[2]), 'values': [24] }], label=list(pie_dict.keys())[5], method="restyle", ), ]), direction="down", pad={"r": 10, "t": 10}, showactive=True, x=0.1, xanchor="left", y=button_layer_1_height, yanchor="top", ), ] ) which leads into javascript: "updatemenus":[{"buttons":[ {"args":[{"labels":["test1"],"marker":{"colors":["#999999"]},"values":[24]}],"label":"25.02.23","method":"restyle"}, {"args":[{"labels":["test2"],"marker":{"colors":["#000000"]},"values":[24]}],"label":"21.02.23","method":"restyle"}], "direction":"down","pad":{"r":10,"t":10},"showactive":true,"x":0.1,"xanchor":"left","y":1.08,"yanchor":"top"}]}, {"responsive": true} ) }; -
connect to dockerized postgres db from django
i got this error message when i try to connect to dockerized postgres db from outside: django.db.utils.OperationalError: connection to server at "172.19.0.2", port 5432 failed: Operation timed out Is the server running on that host and accepting TCP/IP connections? django settings.py: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '172.19.0.2', 'PORT': '5432', 'NAME': 'devdb', 'USER': 'devuser', 'PASSWORD': 'pass123', } docker-compose: db: image: postgres:13-alpine volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=pass123 i did docker-compose up, i tried to change the host ip to localhost but with no success. i tried to chagne the host ip to localhost, i checked that the db is created via psql, i used the ip from docker inspect, any ideas? -
Django sitemap for dynamic static pages
I have the following in my views.py: ACCEPTED = ["x", "y", "z", ...] def index(request, param): if not (param in ACCEPTED): raise Http404 return render(request, "index.html", {"param": param}) Url is simple enough: path('articles/<str:param>/', views.index), How do I generate a sitemap for this path only for the accepted params defined in the ACCEPTED constant? Usually examples I've seen query the database for a list of detail views. Any help is appreciated! -
Connection to Python debugger failed socket closed in Pycharm
Hi all! I want to set it up the same way as the teacher, but so far unsuccessfully .. an error crashes. Is it really possible to set it up like this on PyCharm Community? I am attaching a fragment from the course on udemy. how to set also? -
My url is not updating when I go to a new page on my Django site
I am building a site in django with a clickable calendrer feature. The user can click on each date and it sends them to a new page which they can book a time on that day for a session. The issue is that the URL once the user clicks on the date they want stays the same as the first page. E.g First page http://127.0.0.1:8000/mainsite/book_now after clicking on a date http://127.0.0.1:8000/mainsite/book_now but it should be http://127.0.0.1:8000/mainsite/time_booking but the html of that page is loading but the view function for the page is not running def book_now(request): if request.method=='GET': return render(request, "client_mainsite/book_now.html") elif request.method == "POST": date = str(request.POST.get("date")) context = { } response = render(request, 'client_mainsite/time_booking.html', context) response.set_cookie('date', date) print(date) return response return render(request, "client_mainsite/book_now.html") def time_booking(request): if request.method=='GET': return render(request, "client_mainsite/time_booking.html") elif request.method == 'POST': context = { 'date':request.COOKIES['date'], } time = request.POST['time'] print("below is time") print(time) print("above is time") response = render(request, 'client_mainsite/time_booking.html', context) response.set_cookie('time', time) print(time + "checker") return response urlpatterns = [ path('book_now', views.book_now, name="bookNow"), path('contact_us', views.contact_us, name="contactUs"), path('session_history', views.session_history, name="sessionHistory"), path('booked', views.booked, name="booked"), path('detail_updater', views.detail_updater, name="detailUpdater"), path('session_list', views.session_list, name="sessionList"), path('no_go_time_day', views.no_go_time_day, name="noGoTimeDay"), path('time_booking', views.time_booking, name="timeBooking"), ] -
How to clear browser cache using Django?
I have to clear the browser cache in a project. Is it possible to access the browser cache and clear it through Django? I have no idea. All we are doing is doing a hard refresh by the client. -
Django-rest-framework IF statement in post method is not executing
(I will provide full code at the bottom) I am trying to create an API view with django rest framework. I wanted to create a login API so I was first testing out on how to check if a data exists in a field in the database. Here are the "fields = values" that I want to check that actually exists in the database: pengerja_id = 123 //correct data password = 123 Now for example I want to try inputting the wrong value: pengerja_id = 555 //wrong data password = 555 Now, I run an if queryset.exists() statement. Whenever I gave pengerja_id a wrong value like '555' it executes the else statement as queryset returns false. But whenever I gave it the correct value of '123', It fails to execute the WHOLE code for some reason starting from if serializer.is_valid(). Here is the code inside view.py class AuthorizeMemberView(APIView): serializer_class = AuthorizeMemberSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): pengerja_id = serializer.data.get('pengerja_id') password = serializer.data.get('password') print(f'pengerja_id={pengerja_id}, password={password}') queryset = COOL_YOUTH_MEMBER.objects.filter(pengerja_id = pengerja_id) if queryset.exists(): return Response({'Success':'User Verified'}, status=status.HTTP_202_ACCEPTED) else: return Response({'Login Failed':'User not registered'}, status=status.HTTP_404_NOT_FOUND) return Response({'Bad request':'Data failed to submit'}, status=status.HTTP_400_BAD_REQUEST) Here is the code inside serializers.py class … -
Validation in django rest
I am new to Django and I need help to understand how validation works in serializer and in views. I have created a custom validator and included it in REST_FRAMEWORK in settings.py I notice that some validations are not caught in serializers but are in views or vice versa. For example if I try to validate if all required fields are included in the body request validation validation with custom message works in view but in serializer it gives the standard error message, so the custom validation class is not called. Below code or my custom validation from rest_framework.views import exception_handler from http import HTTPStatus from typing import Any from rest_framework.views import Response def api_exception_handler(exc: Exception, context: dict[str, Any]) -> Response: """Custom API exception handler.""" # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) print(response) if response is not None: # Using the description's of the HTTPStatus class as error message. http_code_to_message = {v.value: v.description for v in HTTPStatus} error_payload = { "error": { "status_code": 0, "message": "", "details": [], } } error = error_payload["error"] status_code = response.status_code error["status_code"] = status_code error["message"] = http_code_to_message[status_code] error["details"] = response.data response.data = error_payload … -
Python Passanger error while deploying via cPanel
I created an app using Django, and using this instruction wanted to deploy it, but the following error shown when loading the page. Stdout and stderr output Error: enterLve() failed: Failed to enter namespace for user *** UID 1001 errno 22 cause Invalid argument Using passenger_wsgi.py import os import sys from djangoinbi.wsgi import application sys.path.insert(0, os.path.dirname(__file__)) environ = os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoinbi.settings") wsgi.py """ WSGI config for djangoinbi project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoinbi.settings') application = get_wsgi_application() Which steps should i follow to debug that? I've tried several similar methods, but still app won't run. -
Getting Users with react and a django/websocket backend
I written code to connect to a web socket from react to a django/daphene websocket. The only problem is that when i try calling self.scope['user'] I get a lazy channel object that has no information. Here's my consumer code import json import datetime import bleach import re from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Message clients = list() class Consumer(WebsocketConsumer): def connect(self): clients.append(self) self.room_name = self.scope['url_route']['kwargs']['room_name'] self.user = self.scope['user'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name, ) # Keeps track of online users async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'user_list', } ) self.accept() and here's my react websocket code const socket = (window.location.protocol === 'https:') ? 'wss://' : 'ws://'; const chatSocket = new WebSocket('ws://127.0.0.1:8000/ws/blap/'); let clients = [] // This gives us the websocket data from the server const useWebSockets = () => { React.useEffect(() => { chatSocket.onopen = () => { console.log('connected to chat socket'); } I think maybe i need the authenticate the websocket with a csrf token but im unclear on how to do that. logging in and out of the application to see if it does anything self.scope['user'].get_username() -
I got error when I run python manage.py makemigrations
When I run python manage.py makemigrations I got this error: (venv) ubuntu@ip-172-31-44-136:~/easy_django_repo$ python manage.py makemigrations /home/ubuntu/venv/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "Scribe3501" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "Scribe3501" warnings.warn( No changes detected This is my database in setting.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "Uninsured4645", "USER": "Scribe3501", "PASSWORD": "****", "HOST": "localhost", "PORT": '' } } I tried to reset my password with: CREATE USER ubuScribe3501t WITH PASSWORD '****'; -
Django OAuth2 authentication error: "invalid_client"
I'm trying to implement OAuth2 authentication in my Django web app using the django-oauth-toolkit package. I've registered my app on the OAuth2 provider and obtained the client ID and secret. However, when I try to get an access token using the authorization code, I'm getting the following error: {'error': 'invalid_client'} I've double-checked that the client ID and secret are correct, and that the redirect URI is set to the correct value in both the provider and the Django app. What could be causing this error, and how can I fix it? Any help would be greatly appreciated! Here is some of the relevant code : url.py for the project : from django.urls import include, path from django.conf.urls.static import static from django.conf import settings from rest_framework import routers from oauth2_provider.views import TokenView, RevokeTokenView, ApplicationRegistration router = routers.DefaultRouter() urlpatterns = [ path('', include(router.urls)), path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), path('o/token/', TokenView.as_view(), name='token'), path('o/revoke_token/', RevokeTokenView.as_view(), name='revoke-token'), path('o/applications/register/', ApplicationRegistration.as_view(), name='register'), path('admin/', admin.site.urls), path('api/', include('vessels.urls')), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('', include('users.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py : from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-!b4#vvo$e(i*o*g61wz1@l0*6p16imxf$c2f1q4-ag==q1kril' DEBUG = True ALLOWED_HOSTS = [] CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third-party … -
How can i post image to django server for use yolo algorithm
We are devoloping a project. We want to use yolo object detection algorithm in a django server and give api a computer which using python. We will post every frame of the camera to server. We want to that server give frame and run yolo or some other algorithm. How can we post frame (image). -
How to print HTML content from a Django template in a view?
Let's say I have a template called index.html with a bunch of block tags and variables and URLs. I can display it from my view using the render() function like so: def index(request): return render(request, "index.html", {...}) I would like to print the actual content that is being generated here in a normal python function. Something like this: def get_html(): html_content = some_function("index.html", {...}) # Takes in the template name and context print(html_content) Is this possible to do using Django? Thanks for any help!