Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to Add microsoft login to python django web app
The web app works with a basic user management service. Im trying to add microsoft authentication through 365. After attempting to log in there is always an error "AADSTS700016: Application with identifier 'None' was not found in the directory 'University Of x'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.' I cannot figure out how to get the URL to include the client ID. I have already created the microsoft social app in the web app's django admin pannel and already tried many syntaxes for putting it in the settings.py. I also just manually put it in the URL and then it crashes the website, Im pretty sure this is because i manually put the client_ID and the backend isnt reading it to process it in the next page. -
drf url parameter lookup
I'm creating an endpoint api/users/ with Django REST framework which should return some data about the user by id. It's all good, but I want to obtain a lookup parameter for my User model from the url's parameters. There are lookup_field and lookup_url_kwarg attributes of GenericAPIView, but they seem to be useless here, because they work with parameters specified in URLConf, if I understand it right. So, my question is how to get object from the db when I go to like /api/users?uid=123? There is surely a way where we override get_object() or get_queryset() or any other stuff like this: class UserAPIView(RetrieveUpdateDestroyAPIView, CreateAPIView): serializer_class = users.serializers.UserSerializer queryset = users.models.User.objects.all() def get_object(self) -> User: uid = self.request.query_params.get('uid', None) if uid is None or not uid.isdigit(): raise Http404 self.kwargs.update({self.lookup_field: uid}) return super().get_object() but it looks kind of ugly, isn't it? I believe there should be a better way of dealing with it.. -
Conditional aggregate and distinct
Using StringAgg with the distinct=True argument works under normal circumstances, e.g.: entities = entities.annotate(roles=StringAgg( "credits__role__name", delimiter=", ", distinct=True, ordering="credits__role__name" )) But when used with a conditional expression, it throws the exception django.db.utils.ProgrammingError: in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list, e.g.: releases = releases.annotate(credits_primary=StringAgg( Case(When(credits__type="primary", then="credits__entity__name")), delimiter=", ", distinct=True, ordering="credits__entity__name" )) Why is this, and is there a way to make the second example work? -
How to sign an XML document with Python?
I am doing a project in Django (full Python) specifically a sales system. Now, I want to incorporate electronic invoicing to the system, focusing only on the electronic sales receipt for now. In my country, the regulatory entity requires that to send the invoice, it must be done in an XML file (with a specific format), then, it must be signed with the digital certificate of the company, packed in a .zip file and sent to the testing web service of the entity. But, I don't know how to do the signature using only Python. I was researching and I noticed that most of them choose to use languages like Java or C#, mainly. I also found the lxml and cryptography libraries, with which I could make the signature, but when I send it to the web service, I get the error: Error of the web service: The entered electronic document has been altered - Detail: Incorrect reference digest value I was trying to find out how to fix this error, I don't know if it has to do with the way I'm signing the XML document or the method I'm using. I share with you the code to give … -
Custom template conditon in Django
In my Django project I want to hide menu option under a custom built condition. In my base.html I want a construction like this: {% if my_condition %} <a class="dropdown-item" href="...">New article</a> {% endif %} How to write 'my_condition'? I searched for 'custom template condition', but they all the answers direct me to the 'custom template tags and filters' of the Django documentation, but I can't find a satisfying solution. -
Django persistent connections with PgBouncer?
We have database performance issues and I am looking into adding PgBouncer to handle connections more efficiently and hopefully solve the issue. However, after configuring it, I am not sure how to tell whether PgBouncer is handling connections as intended (if at all) and in a healthy and effective way. I think the key is deciding whether Djang's CONN_MAX_AGE setting should be set to 0 or to None. This answer says it should be None for persistent connections. But wouldn't this defeat the purpose of PgBouncer's connection pooling? Wouldn't we want to set it to 0 and release connections back to the pool instead? I set PgBouncer's verbosity level to 3, let me paste my log when CONN_MAX_AGE is None and when it is 0, hopefully it tells you something relevant that I myself can't see: CONN_MAX_AGE = None 2025-02-27 12:15:02.832 UTC [3336] NOISE safe_send(23, 577) = 577 2025-02-27 12:15:02.832 UTC [3336] NOISE sbuf_process_pending: end 2025-02-27 12:15:02.832 UTC [3336] NOISE resync(20): done=577, parse=577, recv=577 2025-02-27 12:15:02.832 UTC [3336] NOISE S-0x1a8a698: dbname/dbuser@127.0.0.1:5432 release_server: new state=12 2025-02-27 12:15:02.832 UTC [3336] DEBUG S-0x1a8a698: dbname/dbuser@127.0.0.1:5432 reuse_on_release: replication 0 2025-02-27 12:15:02.836 UTC [3336] NOISE resync(23): done=0, parse=0, recv=0 2025-02-27 12:15:02.836 UTC [3336] NOISE safe_recv(23, 4096) … -
Unable to create a django.conf file for nginx
I am trying to deploy my django app on aws ec2 and i created a django.conf file for nginx this is my django.conf file server{ listen 80; server_name 15.206.160.34; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/{project}/app.sock; } } but when i try to run the command sudo nginx -t i get this error 2025/02/27 10:40:17 [emerg] 15034#15034: directive "proxy_pass" is not terminated by ";" in /etc/nginx/sites-enabled/django.conf:10 nginx: configuration file /etc/nginx/nginx.conf test failed How do i fix this, please help. -
How to set the media path to root media folder in Django?
I have a media folder outside the APP, in the project folder (to share media with other apps). How to set up Django, to set media path to a folder in the project folder? Problem: I'm getting error: "GET /soupiska/pic/hraci/download_6BVC8qn.jpeg HTTP/1.1" 404 2971 but "soupiska" is the APP folder. The path saved in the database is: pic/hraci/download_6BVC8qn.jpeg And settings.py includes: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') print(MEDIA_ROOT) -
weasypring-django __init__() takes 1 positional argument but 3 were given
I am facing problems trying to generate pdf from my django views using weasyprint-django views.py def schoolSequenceReportpdf(request,slug,pk,seq): host=request.META['HTTP_HOST'] if request.user.is_authenticated: skoll = None valuecheck = None admin_check = False statistics = None if request.user.is_school: #Calling the check school profile obj. skoll,valuecheck = check_for_skolProfile(request.user) # Calling the check accademic year object. accademic_yearObj,acc_valuecheck= check_for_accademicYear(skoll) else: try: valuecheck= True skoll= schoolProfile.objects.get(slug=slug) accademic_yearObj,acc_valuecheck= check_for_accademicYear(skoll) admin_check = adminCheck(request.user,skoll) if admin_check is False: return redirect('main:wrongpage') except: return redirect('main:wrongpage') if accademic_yearObj: #get classroom instance try: classroomobj = Level.objects.get(id=pk) sequence = Sequence.objects.get(id=seq) term = sequence.term except: term = None classroomobj = None else: term = None classroomobj = None sequence_report_cards = FinalTermReport.objects.filter(sequence=sequence,classroom=classroomobj).order_by("-studentavg") statistics = ClassroomResultStatistics.objects.filter(sequence=sequence,classlevel=classroomobj,seqstate=True).order_by("-created") terms = Term.objects.filter(year=accademic_yearObj) sequences = Sequence.objects.filter(year=accademic_yearObj).order_by('-created') color = ReportCardColor.objects.filter(skoll=skoll) if color: color= color.first filling_session = FillMarksDateScheduling.objects.filter(year=accademic_yearObj,skoll=skoll,active=True,delete=False) context = {'color':color,'host':host,'statistics':statistics,'sequence_report_cards':sequence_report_cards,'sequence':sequence,'term':term,'filling_session':filling_session,'sequences':sequences,'statistics':statistics,'terms':terms,'admin_check':admin_check,'classroomobj':classroomobj,'name':classroomobj.name,'accademic_yearObj':accademic_yearObj,'accyear':acc_valuecheck,'skollobj':skoll,'valuecheck':valuecheck} html_string = render_to_string("main/sequencereportcardpdf.html", context) pdf = HTML(string=html_string).write_pdf() response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="{classroomobj.name}.pdf"' return response urls.py url(r'^sequence/report/pdf/(?P<slug>[\w-]+)/(?P<pk>[0-9]+)/(?P<seq>[0-9]+)$',views.schoolSequenceReportpdf,name="sequencereportpdf"), I have tried changing errors i got File "/mnt/e/digolearnsms/smsdigo/main/views.py", line 4460, in schoolSequenceReportpdf pdf = HTML(string=html_string).write_pdf() File "/mnt/e/digolearnsms/myenvubuntu/lib/python3.8/site-packages/weasyprint/__init__.py", line 259, in write_pdf self.render(font_config, counter_style, **options) File "/mnt/e/digolearnsms/myenvubuntu/lib/python3.8/site-packages/weasyprint/document.py", line 390, in write_pdf pdf = generate_pdf(self, target, zoom, **options) File "/mnt/e/digolearnsms/myenvubuntu/lib/python3.8/site-packages/weasyprint/pdf/__init__.py", line 127, in generate_pdf pdf = pydyf.PDF((version or '1.7'), identifier) TypeError: __init__() takes 1 positional argument … -
Working directory structure for a Django-Python project used as an API backend only
I'm a newbie in Django Python and I need to create an API backend for a frontend done in React. I'm forced by the customer to use Django Python, no options on this! The project is very simple: it needs to expose ~15 endpoints, use Django ORM to connect to a PostgreSQL database, and have basic business logic. I must have a minimum of 80% unit tests coverage of the code and expose a swagger UI. My problem is to create a "standard", well-defined, wisely organized structure of the working directory structure as defined by the best practice. In .NET I put my endpoints in the controllers, then I create the business logic with interfaces and the data layer where I have the model and the entities, so everything is all well organized and separated. How can I achieve a similar organization in Django? I've seen that some people use DRF (Django RESTful framework), is it good for my purpose? is it a best practice for projects like mine? -
I need to create a system that has custom views for my users
how do large companies or large systems to have several views (screens or UI's) for their different types of users, for example, having a UI for the admin panel, another UI for employee profile and that average users do not enter the admin panel? I know with authorization and authentication, but how do you program it? How do they do it? I'm using Django and I'm using a decorator login required and user_passes_test(lambda u: check_group(u, 'RRHH'), login_url='/denegado/'). and what that does is see if the user who is logged in belongs to HR shows the view, if not, it redirects him to denied and denied redirects him to the view to which he belongs, look: def redirigir_por_grupo(request): if request.user.groups.filter(name='RRHH').exists(): return redirect('sucursales') elif request.user.groups.filter(name='Gerentes').exists(): return redirect('gerencia') elif request.user.groups.filter(name='Empleados').exists(): return redirect('perfil') but I don't know, I feel that it is not the safest and most optimal way, I think right. To tell the truth, it is the first time that I have made such a complex and full stack system and I am interested in it being extremely secure and following the best practices. I want HR to have access to all apps and managements only to incidents and employees only to … -
How to resolve circular dependency error in django models
I have 2 apps in my django project 1.customer app 2.trades app Customer app has following tables in models.py 1.customer_table 2.trade_plan_table 3.service_plan_table 4.customer_payments trades app has following table in models.py 1.trade_details_table 2.service_details_table Below are my dependencies: 1.service_plan_table has foreign key ref to service_details_table 2.customer_payments has foreign key ref to customer_table, trade_plan_table, service_plan_table trade_details_table has foreign key ref to customer_table service_details_table has foreign key ref to customer_table Since there is dependency from customer model to trades model and vice versa, I'm facing circular dependency error. Instead of importing I tried 'string reference' but it did not help. Can some one please suggest how to solvethis issue -
Django form field labels are not displaying in the template
whats wrong with this code? labels are not displaying in the 'single-project.html' template. can anyone tell the mistake in this code.what should i correct it to display my labels in my template. My forms file class ReviewForm(ModelForm): class Meta: model = Review fields = ['value', 'body'] labels = { 'value' : 'Place your vote', 'body' : 'Add a comment with your vote' } def __init__(self, *args, **kwargs): super(ReviewForm, self).__init__(*args, **kwargs) for name,field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) My views file def project(request,pk): projectObj = Project.objects.get(id=pk) form = ReviewForm() return render(request,'projects/single-project.html', {'project' : projectObj, 'form':form,}) My template file {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#textarea">{{field.label}}</label> {{field}} </div> {% endfor %} solution to this problem -
REACT Component for Car Dealerships Page Not Visible
I am working through IBM Coursera's Full Stack Developer course and am stuck on the Car Dealership application Capstone Project. Specifically, I am struggling to make the car dealerships visible on the dealers page. A semicolon appears on the page. This makes it seem as though the Dealers.jsx React component is not correctly rendering, but that was provided by IBM so I would not think that contains any errors. Current output of Dealerships page Dealers page output Dealers.jsx React component (provided by IBM) import React, { useState, useEffect } from 'react'; import "./Dealers.css"; import "../assets/style.css"; import Header from '../Header/Header'; import review_icon from "../assets/reviewicon.png" const Dealers = () => { const [dealersList, setDealersList] = useState([]); // let [state, setState] = useState("") let [states, setStates] = useState([]) // let root_url = window.location.origin let dealer_url ="/djangoapp/get_dealers"; let dealer_url_by_state = "/djangoapp/get_dealers/"; const filterDealers = async (state) => { dealer_url_by_state = dealer_url_by_state+state; const res = await fetch(dealer_url_by_state, { method: "GET" }); const retobj = await res.json(); if(retobj.status === 200) { let state_dealers = Array.from(retobj.dealers) setDealersList(state_dealers) } } const get_dealers = async ()=>{ const res = await fetch(dealer_url, { method: "GET" }); const retobj = await res.json(); if(retobj.status === 200) { let all_dealers = Array.from(retobj.dealers) let … -
Failed to execute 'setRemoteDescription' on 'RTCPeerConnection' on webrtc
So I am following the tutorial by TauhidCodes on youtube here: https://www.youtube.com/watch?v=MBOlZMLaQ8g It is a little different because I am using reverse urls for the different room names. I am implementing a video call system that allows more than 3 users and above to join by entering the appropriate url like https://127.0.0.1:8000/video/test/. I open 2 tabs in the same window and press start call for both of them and they both say the error. Error test/:1 Uncaught (in promise) InvalidStateError: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable <!DOCTYPE html> <html> <head> <style> button { border: 0; background-color: orange; padding: 10px; color: white; border-radius: 7px; } video { border-radius: 15px; } .videoContainer { display: flex; margin: 20px; width: 640px; } .videoContainer h2 { color: white; position: relative; bottom: -380px; left: -350px; width: max-content; } #meet { display: flex; } #recordButton.recording { background-color: red; } #downloadButton { background-color: #4caf50; } button:disabled { background-color: #cccccc; cursor: not-allowed; } </style> <title>A Free Bird Video Call</title> <script src="https://meet.jit.si/external_api.js"></script> </head> {% load static %} <body> <div id="meet"> <button id="videoOff" onclick="toggleVideoOff()" disabled>Video Off</button> <button id="audioMute" onclick="toggleAudioMute()" disabled>Mute Audio</button> <div id="remote-videos"> <div id="videoContainer"> <video id="localVideo" autoplay playsinline></video> <h2>{{ … -
what has happened to the add view in Wagtail 6.x
Upgrading from Wagtail 5.2.6 to Wagtail 6.3 LTS, I noticed that the methods add and edit that were here are no longer there: wagtail.images.views.images What happened to them? Were they moved or replaced? -
Linked tables/models in Django - more than Foreign Keys
I am designing a Django project, where I need the following (I want to implement something more complex, but simplified here): Table: work_order Columns: owner_id, ..., contract_file_id (maps to 'all_files.id') Table: labour_license Columns: owner_id, ..., license_file_id (maps to 'all_files.id') Table: all_files Columns: id (UUID4Field), category (CharField, 'contract' if linked to 'work_order.contract_file_id', 'labour_lic' if linked to 'labour_license.license_file_id') file (FileField) ... Anytime a file is uploaded to work_order, it should insert a row in all_files with category='contract'; similarly for labour_license. Anytime a file with a particular UUID4 is to be accessed, I would like to query back the owner_id (in work_order table if all_files.category='contract'; similarly for labour_license. I have literally 10s of file fields like this, and I would like to write some kind of Mixin or custom Field, or even a metaclass if required, which I can use for all such file fields. If it is possible, would appreciate some ideas or directions I can look into. -
I am generating the pdf file in django, here i am using @font-face for USPSIPStandard for just one <p> tag, but it is affecting the whole pdf
I am generating the pdf reports for the patient using wkhtmltopdf in Django, and i have to show the patient imb_code in USPSIPStandard font family ,I am using its file in Static folder, when use this @font-face in my html file, this is affecting the tag styling,(not the text showing in USPS format but only the style is changing) but i am not using this font face on this pre tag, <style> @font-face { font-family: 'USPS_IMB_Standard'; src: url("{{ usps_font }}") format('truetype'); } /* Apply only to specific class */ .usps-barcode { font-family: 'USPS_IMB_Standard', sans-serif; } </style> // Here is pre tag <pre style="padding: 10px 5px; font-size: 12px"> {{statement.statement_data}}</pre> // Here using this font family: <div> <p class="usps-barcode" style="font-size: 14px; margin: 5px 5px 0px; padding: 0px; margin-left: 1px;"> {{ patient.imb_encode }} </p> </div> but when i remove this : @font-face { font-family: 'USPS_IMB_Standard'; src: url("{{ usps_font }}") format('truetype'); } it show the pre tag content in proper format,why font-face is affecting the pre tag, altough i am not applying it on pre tag , as i also define the default body and * font-family -
Store ONNX Models in PostgreSQL with Django
I am working on a Django project where I need to store ONNX models in a PostgreSQL database. Currently, I am considering using a BinaryField to store the model files as blobs, but I get a memory error. Is there a more efficient or Django-friendly approach to storing ONNX models in PostgreSQL? -
Looking for Inspiration & Recommendations for My Upcoming POS Project using Django [closed]
👋 I'm planning to build a Point of Sale (POS) system using Django, and I’m looking for recommendations and inspiration. I want to make it efficient, user-friendly, and scalable. Are there any open-source POS projects in Django that you'd recommend for reference? -
In django transactions, what happens if an error is raised in on_commit?
Situation I have a postgres database, and I'm using django transaction's on_commit hook to do something (in this case move a file but it doesn't really matter what for the purposes of the question) once the save of a model has been committed to the database. from django.db import models, transaction def my_oncommit_callback(): # Do something on commit raise ValueError("what if I raise an error") class MyModel(models.Model): def save(self, *args, **kwwargs): transaction.on_commit(my_oncommit_callback) super().save(*args, **kwargs) The Question If my_oncommit_callback raises an error, is the transaction rolled back, or will I get a broken state because my on_commit function hasn't worked as expected? -
pytest_django model class attribute not filled for __init_subclass__
I have a specific problem. class A: SOME_ATTR: int def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) attr = getattr(cls, "SOME_ATTR", None) if not attr: raise TypeError(f"Class '{cls.__name__}' must define 'SOME_ATTR'") classB(models.Model, A): SOME_ATTR = 0 In this case everything works as expected but pytest tests. pytest_django creates: cls = <class 'fake.B'> which has no attribute 'SOME_ATTR' Is there any option to enforce it? I'v tried to add a session scope autouse fixture but it didn't work as it happens before it. -
How to Structure a Django Project for a Multi-questuinnaire System and Import Questions in Bulk?
I'm building a Django project that will host dozens of questionnaires. I have a few architectural and implementation questions: 1)Should I create a separate app for questionnaires and another app for test takers within the main Django projectand put models like User _Answer and Test_Result within the test takers app itself? 2)In the test model, how can I design the database structure to handle different question types? Some questions are only text-based, some are only image-based, and some contain both text and images. 3)Since each test may contain hundreds of questions, manually entering them via the Django admin panel is impractical. Is there a way to bulk import questions from a Word document? I appreciate any insights or best practices for handling these challenges in Django. -
Django TypeError: 'Category' object is not iterable in template loop
1️⃣ Problem Description: I'm working on a Django project where I'm trying to display a category and its associated products. However, I'm getting the following error in my template: 2️⃣ Error Message: TypeError at /category/2/'Category' object is not iterableRequest Method: GETRequest URL: http://127.0.0.1:8000/category/2/Django Version: 5.1.4Exception Type: TypeErrorException Value: 'Category' object is not iterableException Location: C:\Users\brahm\OneDrive\Desktop\Django\one\Lib\site-packages\django\template\defaulttags.py, line 198, in renderRaised during: accounts.views.categoryPython Executable: C:\Users\brahm\OneDrive\Desktop\Django\one\Scripts\python.exePython Version: 3.11.5Python Path: ['C:\Users\brahm\OneDrive\Desktop\Django\one\Scripts\user_authincation','C:\Program Files\Python311\python311.zip','C:\Program Files\Python311\DLLs','C:\Program Files\Python311\Lib','C:\Program Files\Python311','C:\Users\brahm\OneDrive\Desktop\Django\one','C:\Users\brahm\OneDrive\Desktop\Django\one\Lib\site-packages']Server time: Wed, 26 Feb 2025 06:25:55 +0000 3️⃣ My Django View (views.py): `def category(request,id): categories =Category.objects.get(id=id) products=Product.objects.filter(category=categories) context={ 'categories':categories, 'products':products, } return render(request,'category.html',context)` 4️⃣ My Django Template (category.html): {% for category in categories %} <a class="nav-link" href="/category/{{category.id}}/">{{category.name}}</a> {% endfor %} urls.py urlpatterns=[ #path('home',home,name='home'), #path('',register,name='register'), #path('login/',login_user,name='login'), #path('logout/',logout_user,name='logout'), path('category/<int:id>/',category,name='category'), ] models.py class Category(models.Model): name=models.CharField(default='uncategorized',max_length=100) is_active=models.BooleanField(default=True) def __str__(self): return self.name class Product(models.Model): category=models.ForeignKey(Category,on_delete=models.CASCADE,related_name='categories') product_name=models.CharField(max_length=120) img=models.ImageField(upload_to='photos/') created_date=models.DateTimeField(auto_now=True) desc=models.TextField() price=models.CharField(max_length=8) def __str__(self): return self.product_name 5️⃣ Expected Behavior: I want to display the category name and list of products under it. 6️⃣ Issue: Since category is a single object, it is not iterable, but my template uses {% for category in categories %}. 7️⃣ My Question: What is the correct way to access a single object in a Django template? Should I change my view … -
Django-storages inserting bucket name as a folder
I'm migrating to Django 5.1.6 (django-storages 1.14.5) from Django 3.2 using DigitalOcean S3-compatible Spaces and when I run python manage.py collectstatic the bucket name is being inserted as a folder when it used to not be. I want it to be stored in myBucket as /static/myFile.png, but it's being stored as /myBucket/static/myFile.png instead. In my settings.py file: STORAGES = { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": { "secret_key": "mySecretKey", "access_key": "myAccessKey", "bucket_name": 'myBucket', "endpoint_url": 'https://mySubdomain.sfo2.digitaloceanspaces.com/', "object_parameters": {'CacheControl': 'max-age=86400'}, "location": 'static', "default_acl": 'public-read', }, }, } STATIC_URL = "https://mySubdomain.sfo2.digitaloceanspaces.com/static/" Am I doing something wrong or is this a bug in the django-storages?