Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inserndo valores nulos no postgres atraves do django
Escrevi um código que recebe imagens do formulário html e as converte em valores binários e insere no postgres, desta forma tudo fica funcional mas quando não insiro nada no formulário html e clico no botão enviar dá um erro, isso quer dizer que não devo enviar campos de arquivo null para o django. gostaria de saber se existe alguma forma de inserir valores nulos no postgres através do django mas recebendo do formulário html o codigo python : def document(request): if request.method=='POST': uuid = request.POST['uuid'], facilitador = request.POST['facilitador'], enumerador = request.POST['enumerador'], certificado_ref = request.POST['certificado_ref'], provincia = request.POST['provincia'], distrito = request.POST['distrito'], comunidade = request.POST['comunidade'], provedor = request.POST['provedor'], observacao = request.POST['observacao'], data_submissao = request.POST['data_submissao'], data_certificado = request.POST['data_certificado'], img_mapa = request.FILES["img_mapa"].read() img_certificado = request.FILES["img_certificado"].read() formulario1 = request.FILES["img_formulario1"].read() formulario2 = request.FILES["img_formulario2"].read() formulario3 = request.FILES["img_formulario3"].read() formulario4 = request.FILES["img_formulario4"].read() formulario5 = request.FILES["img_formulario5"].read() img_historia = request.FILES["img_historia"].read() map_mulheres = request.FILES["map_mulheres"].read() map_homens = request.FILES["map_homens"].read() map_jovens = request.FILES["map_jovens"].read() map_idosos = request.FILES["map_idosos"].read() cartograma = request.FILES["map_cartograma"].read() img_estatutos = request.FILES["img_estatutos"].read() img_coordenadas = request.FILES["map_coordenadas"].read() try: try: insert_script="INSERT INTO public.delimited_community_geoportal_source (uri,facilitator,enumerator,certificate_ref,province_id,district_id,community_name,financer,obs,submission_date,certificate_date,img_sketch_map,img_certificate,img_form_1,img_form_2,img_form_3,img_form_4,img_form_5,img_history,img_maps_men,img_maps_women,img_maps_youth,img_maps_old,img_cartograma,img_statutes_assoc,img_coords) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" insert_values = (uuid,facilitador,enumerador,certificado_ref,provincia,distrito,comunidade,provedor,observacao,data_submissao,data_certificado, psycopg2.Binary(img_mapa),psycopg2.Binary(img_certificado),psycopg2.Binary(formulario1),psycopg2.Binary(formulario2),psycopg2.Binary(formulario3),psycopg2.Binary(formulario4),psycopg2.Binary(formulario5), psycopg2.Binary(img_historia),psycopg2.Binary(map_mulheres),psycopg2.Binary(map_homens),psycopg2.Binary(map_jovens),psycopg2.Binary(map_idosos), psycopg2.Binary(cartograma),psycopg2.Binary(img_estatutos),psycopg2.Binary(img_coordenadas),) cur.execute(insert_script,insert_values) conn.commit() messages.success(request, "Ficheiro carregado com sucesso") except(Exception, psycopg2.Error) as error: messages.success(request, "Erro no carregamento do ficheiro",error) finally: pass context = { } return render(request,'document.html', … -
django sub admin panel
I am working on the Django admin panel but now client is asking me that he need a functionality to create sub admin from the admin panel and provide some permission to sub admin flow - Here admin need a tab like sub admin management- admin will be able to create new admin by providing email, name photo, once admin submit the details of the sub admin link will be shared to the sub admin inputted email from where he can set his password, admin will also have the functionality to provide different permission to different sub admin, will be able to change these permission in future i have 6 application in admin where admin is admin to perform cur operation on user management, device management. i.e permission for sub admin will be for example sub admin can view user management but view and edit device management and so on. Questions How we can register the sub admin? i.e to register the super admin we go to terminal and write the commands to register the sub admin now registration for sub admin is done from admin panel How we can provide different permission to the sub admin Do I need … -
Efficient debugging Django with pdb – like Sentry
I use pdb to debug in Django. Sometimes it works, sometimes it does not catch the issue, just runs over the error. I have another example, the way how Sentry shows the bugs. Exactly at the place where it is relevant. Could I use pdb similarly? Maybe via the "where" command? It would be so useful! An example: if there is a bug in one of the serializers, it is so hard to find the relevant code place. Django server just gives a "non_field_errors":["Something unexpected has occured. Please contact an admin to fix this issue."]. On the other hand, Sentry can show the hot spot. So it "can" be found. I would like to find it with pdb also! -
How to fetch text value dynamically when clicked on it using javascript
I have a DJANGO app and want to get the values of text in JAVASCRIPT when it gets selected but getting undefined instead. my code: <div class="askedDiv"> {% for i in recentlyUsed %} <p onclick="myFunction()" id="myBtn">{{i}}</p> {% endfor %} </div> in js: function myFunction() { const x = document.getElementById("myBtn").value; console.log(x) } but in console i'm getting undefined. How can i get different text name , when it is selected from recentlyUsed list. As I'm new to this anyhelp will be thankfull. -
How to change state (FSM) of Aiogram bot outside of message handlers?
I have Aiogram bot workings inside Django REST server. If there is POST request coming in Django I need to change the state of Aiogram bot, but I don't know how to do it outside of message handlers and how do I clarify the change of state of specific bot. Mby there is some other ways to solve this? -
How to get data of first column from table in django template
How to get data of first column from table in django template views.py def get_table(request): table = Table.objects.all() return render(request, 'template.html', {'table': table}) template.html {% block 'content' %} <h1 class="title">{{table|first.title}}</h1> {% endblock %} But I'm getting TemplateSyntaxError: Could not parse the remainder: '.title' from 'table|first.title' Database (db.sqlite3): id title 1 Testing title 2 A really good title I have tried to put {% for data in table %} <h1 class="title">{{data.title}}</h1> but that is not the case. -
How to update foreign key from another model Django
I'm fairly new to Django, I have two models usecase and usecase_type. usecase table has a fk of usecase_type. I'm trying to update usecase details including the usecase_type value. How can I update the value plus show the usecase_type in a dropdown list to update. My views.py: def edit_usecase(request, ucid): try: usecase_details = Usecase.objects.filter(usecase_id=ucid) context = {"usecase_details":usecase_details[0]} if request.method == "POST": usecase_name = request.POST['usecase_name'] usecase_description = request.POST['usecase_description'] usecase_type = request.POST['usecase_type'] usecase_details = Usecase.objects.get(usecase_id=ucid) usecase_details.usecase_name = usecase_name usecase_details.usecase_description = usecase_description usecase_details.usecase_type_id = usecase_type usecase_details.save() if usecase_details: messages.success(request, "Usecase Data was updated successfully!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) return render(request, 'UpdateUsecase.html', context) except: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) my template: {% block body %} <div class="row d-flex"> <div class="col-12 mb-4"> <div class="card border-light shadow-sm components-section d-flex "> <div class="card-body d-flex "> <div class="row mb-4"> <div class="card-body"> <div class="row col-12"> <div class="mb-4"> <h3 class="h3">Edit usecase details:</h3> </div> <!-- <li role="separator" class="dropdown-divider border-black mb-3 ml-3"></li> --> <form action="/update-usecase/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="exampleFormControlTextarea1">Usecase name:</label> <input value="{{usecase_details.usecase_name}}" type="text" name="usecase_name" class="form-control" placeholder="" required> </div> <div class="col-lg-8 mr-f"> <label class="h6" for="exampleFormControlTextarea1">Usecase description:</label> <input value="{{usecase_details.usecase_description}}" type="text" name="usecase_description" class="form-control" placeholder="" required> … -
How does OCPP work with the Django rest framework?
I need to create a project with ocpp and Django rest framework I start to create project with ocpp but was not able to connect with the rest framework -
How can i start in cutting stock problem?
I am looking to build a web app (Using React + Django) for 1D and 2D cutting stock problem. After searching for a while i am a bit lost on what can i start with and what algorithms to implement and how. Any help and resources that are recommended to start with would be appreciated. Thank you -
NGINX max upload has no effect
I'm using nginx proxy docker for my django project but I'm getting 413 Request Entity Too Large when uploading images more than about 3MB. I put client_max_body_size 1024M; in htttp, server and location in nginx.conf and default.conf but it doesn't work at all. Should I rewrite any other configs or uwsgi? -
Serializer a input data with list [Django restframework]
I have a question with to declare an input data { “id”: 1235, “products”:[ { “product_id”: 1, “descriptions”: “b” }, { “product_id”: 2, “descriptions”: “a” }, { “product_id”: 3, “descriptions”: “c” } ] } So I have make the serializer like this id = serializers.CharField(write_only=True, required=true) product_id= serializers.Integer()(required=False) descriptions = serializers.CharField(max_lenght=300)<br> products = [serializer.JSONField()] Is it correct for it ? Thank you everyone How get the django serializer for the list of a data -
Django Template tag 'with' not working as expected
I'm trying to use Django Template 'with' tag to alternate between two icons, the solid icon represents liked posts (called chirps in this project), and the regular icon represent non-liked posts(chirps). After some iterations this is the code I'm trying to implement but for some reason the last conditional 'if' always interpret the variable 'blahblah' as False, even when has been reassigned to True: <span style="float: right"> {% with blahblah=False %} {% for like in likes %} {% if like.userId == currentUserId and chirp == like.chirpId %} {% with blahblah=True %} <i id="like{{ chirp.id }}" class="fa-solid fa-heart likeBttn"></i> {% endwith %} {% endif %} {% endfor %} {% if not blahblah %} <i id="like{{ chirp.id }}" class="fa-regular fa-heart likeBttn"></i> {% endif %} &nbsp; <span class="count{{chirp.id}}">{{liked}}{{ chirp.numLikes }}</span> likes {% endwith %} </span> I have tried to use {% empty %} tag but doesn't really apply this problem because 'likes' is never empty. This is the simplest implementation to the problem but unfortunately is not working. -
Django - When using Easy Thumbnails how to force a field to convert the thumbails to JPG even if PNG with alpha was provided
When using Easy Thumbnails you can globally configure that all images (even PNGs with alpha) are converted to JPG by adding this to your settings.py THUMBNAIL_TRANSPARENCY_EXTENSION = 'jpg' But the problem is that I don't want to force ALL of my images in my application to be converted to JPG because I have some models that require images with alpha (png). I have a model for a blog article where I need the image to ALWAYS be converted to JPG. No matter if people upload PNGs with alpha. class Article(BaseModel): title = models.CharField(max_length=255, unique=True) image = ThumbnailerImageField(upload_to='blog/articles/image') Right now many people are uploading PNG's with alpha enabled (although the image doesn't have any transparency) and this is preventing the Thumbnailer to compress them as JPG making many of the thumbnails 500kb(png) instead of like 70kb(jpg). How can I specify to always convert these article images to JPG? -
In Django, is using exclude() before values() actually better for performance or is it just a myth?
In Django QuerySet, while querying, is it really better to use exclude() before values() in a query? For example: query_obj = TestModel.objects.values().exclude(somefield='somevalue') Is this the right way or, query_obj = TestModel.objects.exclude(somefield='somevalue').values() this one? Or both work the same way? -
Deleting many to many objects in django
I have two models like this: class Toppings(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) class Pizza(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) toppings = models.ManyToManyField(Toppings) I create a pizza and add toppings like this crazy_pizza = Pizza(name = "crazy pizza") crazy pizza.save() toppings = ["pepperoni","chicken","bacon"] for i in toppings: topping = Toppings(name = i) toppings.save() crazy_pizza.add(topping) crazy_pizza.save() now i want to delete all the toppings associated with crazy pizza. I run crazy_pizza.toppings.clear() this removes the many to many reference, how can i also delete all the actual toppings objects themselves? -
strict mime type checking is enabled, refused to execute script from '<url>' its mime type ('application/octet-stream'') is not executable, and
i have a problem when to return a html file through a link which is request from an API using django, like this: enter image description here any sugestion for this problem? thank you if there's no problem it will show the data -
Django dont show pdf from database
Learning Django and want show pdf documents from database on html page. But I have error: Unable to connect to site, ERR_NAME_NOT_RESOLVED. models.py class Certificate(models.Model): title = models.CharField(max_length=30, null=True) pdf = models.FileField(upload_to='pdf') status = models.BooleanField(default=True) class Meta: verbose_name_plural='09. Certificates' views.py def certificates(request): certificates = Certificate.objects.filter(status=True).order_by('-id') return render(request, 'certificates.html', {'certificates': certificates}) certificates.html {% block content %} <main class="container my-4"> <h3 class="my-4 border-bottom pb-1">Сертификаты</h3> <div class="row"> {% for certificate in certificates %} <html> <div class="card shadow"> <h1>{{certificate.title}}</h1> <iframe src="//media/{{pdf.pdf}}" width="100%" height="100%"> </iframe> </div> </html> {% endfor %} </div> </main> {% endblock %} I took information in parts through Google, maybe I missed the important setting, but I can't find a solution? Site is running locally on my computer. -
Possible platform to see real-time database changes on a dashboard
I am doing a website using Django that uses AWS RDS Postgresql as the database. Currently, I want put up the database on a dashboard that I can see live changes of the database from the dashboard without having to run the SQL statement SELECT * FROM xxx within my postgresql script everytime I want to see my database updates. Is there anyway I can do this? Is AWS Kinesis suitable? Or are there any other platforms to recommend? -
How to skip the record that creates 500 error in django api?
I have a serialiser and everything is working fine, but when some record that is not json serialiserable is inserted, it gives 500 error. I want to just skip the record that gives the error and get all the data. Error is: File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Country is not JSON serializable [14/Mar/2023 10:15:49] "GET /api/countries/ HTTP/1.1" 500 142117 -
TemplateDoesNotExist at / base/home.html Error
after given the path error in finding template apps are defined and also all path are clear need no run server -
select_related between three or more models
When using select_related in Django, you can get from A to B to a foreign key, you would write the following A.objects.select_related('B')... What should I write if I am referencing a foreign key from B to C? -
how to manage with new programming or framework version releases
Maybe the question will look like it is related to Django but it is a general question. I learned Django 1 year ago and Django version which i learned was 3.2 and now django updated and the version is 4.2. Django course i bought is using same version that i learned 3.2. My question is should i start learning Django again from scratch bcoz they launched new version or i go through the release notes only ? If yes then one more question. Is in release notes they only tell what is updated and the things which are not updated are not mentioned in the release notes. I go through release notes but i am worried like if all core concepts are changed. So i am looking for a industry exprience developer who can answer my question. -
authenticate function returning none in login api view django
I am building registration,login,logout apis with django rest.Registration works properly.I created a login view to authenticate users based on given username and password but authenticate return none instead of the user object.I am using a non hashed password for simplicity and It doesn't work.I can create users via the register api and they are created in the database and although I give the same credentials to the login api it fails.I printed the username and password inside the function before authenticate to test if they hold their correct values and they do but yet fails to authenticate. views.py @api_view(['POST']) def register(request): userser = SignUpUserSerialzer(data=request.data) if userser.is_valid(): user = userser.save(is_active = False) activateEmail(request, user, userser.validated_data['email']) return Response(userser.data) else: return Response(status=status.HTTP_404_NOT_FOUND) @api_view(['POST']) def custom_login(request): # if request.user.is_authenticated: # return redirect(reverse('home')) username=request.data['username'] password=request.data['password'] print(username) print(password) print('login1') user = authenticate(username=username, password=password) print('login2') print(user) if user is not None: login(request, user) return Response({"user": user.id}) else: return Response("error") serializers.py from rest_framework import serializers from .models import CustomUser class SignUpUserSerialzer(serializers.ModelSerializer): class Meta: model = CustomUser fields = '__all__' models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): email = models.EmailField(unique=True) def __str__(self): return self.username settings.py AUTH_USER_MODEL = 'users.CustomUser' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) REST_FRAMEWORK = … -
SynchronousOnlyOperation with django-channels on query done on urls
On the very first request after the application run, I'm facing the following error. It only happens once and after the first request fails, everything continue to work as usual, so I have no idea what's going on. It happened after I adopted async on my Django application: SynchronousOnlyOperation You cannot call this from an async context - use a thread or sync_to_async. ... line 44, in names_regex for n in names: File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 394, in __iter__ self._fetch_all() File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1866, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 281, in __iter__ for row in compiler.results_iter( File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1346, in results_iter results = self.execute_sql( File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1393, in execute_sql cursor = self.connection.cursor() File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) On my urls.py, I have something like this: router = DefaultRouter() router.register(r'news/' + NewsType.objects.names_regex(), NewsModelViewSet, basename='news') NewsType.objects.name_regex() has the code below (where the error is being triggered): def names_regex(self): names = self.get_queryset().values_list('name', flat=True) regex = r'(?P<newstype>' try: for n in names: regex += r'|{}'.format(n) except ProgrammingError: regex += r'|{}'.format('') regex += r')' return regex I also have this on my routing.py: application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter(apps.simulation.routing.websocket_urlpatterns) ), } ) and this my … -
Django: Getting last sent or received message of each user regarding the current user
I'm using Django 4.0 with PostgreSQL v 14. I can't find a way to get the last sent or received message in my database. My code is: class Message(models.Model): """ A model to represent a message between two users. Fields: message (CharField): The text content of the message with a maximum length of 2000 characters. attachment (FileField): An optional file attachment with the message. The file will be uploaded to the 'attachments/' directory. timestamp (DateTimeField): The date and time the message was sent, automatically set to the current date and time when the message is created. sender (ForeignKey): The sender of the message, a foreign key to the User model with a related name of 'sender'. receiver (ForeignKey): The receiver of the message, a foreign key to the User model with a related name of 'receiver'. Methods: __str__: Returns the text content of the message as a string representation of the model. """ objects = MessageManager() message = models.CharField(max_length=2000) attachment = models.FileField(upload_to='attachments/', blank=True) timestamp = models.DateTimeField(auto_now_add=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') deleted = models.BooleanField(default=False) deletedBy = models.ForeignKey(User, on_delete=models.CASCADE, related_name='deletedBy', blank=True, null=True) deletedStamp = models.DateTimeField(null= True)``` I did make the function: def getLastUsers(self, user, nbUsers = …