Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
total number of hires (django)
models.py: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True) full_name = models.CharField(max_length=50,blank=True, null=True) bio = models.TextField() is_hired = models.BooleanField(default=False) hires = models.ManyToManyField(User, related_name="profile_hires",blank=True, default=None) template: <div> <div class="title">Likes</div> <i class="fa fa-group"></i> <div class="value">{{profile.likes.count}}</div> </div> I want it so that it number of hires doesn't decrease, so if i hire someone and then later fire them it should show 1 hire instead of decreasing the count to 0 -
Django Jet Theme Installation + Bookmark collission with Admin_Tools
I keep getting this error when Installing Jet Theme in an environment which uses currently admin_tools. Any idea how to solve it? What do I need to add in Models? All I try with ForeignKeys and related_name ends up in another error. python manage.py makemigrations apfm SystemCheckError: System check identified some issues: ERRORS: apfm.Bookmark: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'added'. jet.Bookmark.user: (fields.E304) Reverse accessor 'User.bookmark_set' for 'jet.Bookmark.user' clashes with reverse accessor for 'menu.Bookmark.user'. HINT: Add or change a related_name argument to the definition for 'jet.Bookmark.user' or 'menu.Bookmark.user'. menu.Bookmark.user: (fields.E304) Reverse accessor 'User.bookmark_set' for 'menu.Bookmark.user' clashes with reverse accessor for 'jet.Bookmark.user'. HINT: Add or change a related_name argument to the definition for 'menu.Bookmark.user' or 'jet.Bookmark.user'. I have tried to give the 'jet.Bookmark.user' and 'menu.Bookmark.user' a related_name using ForeignKeys in models.py but I cannot make it work. -
How to get folium map to full screen width despite being in a bootstrap container?
I am playing around with Folium. The map is contained within a bootstrap container.(tab) As a result, the map is taking the size of the child div instead of the whole screen width. Is there a way to change the map to full screen width despite it being in a child div? (I did try to remove all the divs (except the tab one) but the result is the same) <div class ="container mt-2"> <ul class="nav nav-tabs"> <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#all">All</a></li> <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#other">Other</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="all"> <div class="row"> <div class="col"> {{map|safe}} <div class="col-auto"></div> </div> </div> </div> <div class="tab-content"> <div class="tab-pane" id="other"> <div class="row"> <div class="col"> {{map_access|safe}} <div class="col-auto"></div> </div> </div> </div> </div> </div> -
I am getting data which was fetched for earlier request instead of current request in DJango Restframework + Pandas
I am currently using SOLR as database and Django Restframework as my back-end. here is scenario request 1: fetched 100 records from SOLR and used pandas for manipulating data for response and sent response: Completed successfully no issue request 2: fetched 50 records from SOLR and used pandas for manipulating data for response and sent response but some how previous 100 record get added and now df is 150. Can some one help me in under standing why is this happening Surplus this is only happening on only one server and rest is working fine I tried to log data at each step and it was correct apart from one set of place in for loop. -
Uncaught TypeError: Failed to resolve module specifier "cytoscape". Relative references must start with either "/", "./", or "../"
This is my directory path I'm running cytoscape module on Django server.But terminal throws ERROR Uncaught TypeError: Failed to resolve module specifier "cytoscape". Relative references must start with either "/", "./", or "../". settings.py import os.path STATIC_URL = "/static/" STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ STATIC_DIR, ] print(STATIC_DIR) index.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="UTF-8"> <title>0!</title> </head> <body> <div id="cy"></div> <script type="module" src="{% static '/src/index.js' %}"></script> </body> </html> webpack.config.js const path = require("path"); const HtmlWebPackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: "./src/index.js", output: { filename: "bundle.js", path: path.resolve(__dirname + "/build") }, devServer: { static: { directory: path.join(__dirname, 'public'), }, compress: true, port: 9000, }, mode: "none", module: { rules: [ { test: /\.(js|jsx)$/, exclude: "/node_modules", use: ['babel-loader'], }, { test: /\.html$/, use: [ { loader: "html-loader", options: { minimize: true } } ] }, { test: /\.css$/, use: [MiniCssExtractPlugin.loader,'css-loader'] }, { test: /\.json$/, type: "javascript/auto", use:[ { loader: "file-loader", options: { name: "model/[name].[ext]" }, } ], include: [ path.resolve(__dirname, "./model") ] }, { test:/\.ico$/, use:[{loader:"file-loader?name=[name].[ext]",}], } ] }, plugins: [ new HtmlWebPackPlugin({ template: '../Map/templates/Map/index.html', filename: 'index.html' }), new MiniCssExtractPlugin({ filename: … -
How to restrict Django users from filling a form twice in different sessions
I have a form for employees to fill their bio data, I want to restrict the employees from viewing the form more than once. That is after filling the form, you can’t view the empty form anymore, you can only follow an update link to update the form. I used the Django ‘’’is_authenticated’’’ function for the user registration and login pages, I am looking for a way to do something similar for my current issue. Thanks. -
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 …