Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Entering multiple records and single records at the same time in CreateView
On a page, there are the questions I pulled from the database and the options to choose, and the answering information field at the end of the page. I pulled the questions in the database and printed them. I created form.py and added the respondent information to the page. questions, answers and respondent information in the same form tag. the respondent information is registered in the table, but I cannot record the questions and answers in the answers table. I didn't create form.py for questions and options. class SecDetay_View(CreateView): model = UserIs form_class = UserIsForm template_name = 'sec_detay.html' detayid:int = 0 def get_success_url(self): return reverse('tsk:tskdty', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(SecDetay_View, self).get_context_data(**kwargs) self.detayid = self.isalt_grup_id(self.kwargs['hizmet'], self.kwargs['detay']) context['dtyid'] = self.detayid context['sorular'] = self.sorular context['secenekler'] = self.secenekler return context def form_valid(self, form): kayit = super(SecDetay_View, self).form_valid(form) obj = Cevap(cevap_id=1,soru_id='1',useris_id=self.object)`#my attempts obj.save(self) return kayit `` -
Django + Nginx + Cloudflare - Why is my TTFB so high?
This is my first time setting up a web server using nginx/cloudflare so if there is anything obvious on why my TTFB is so high I apoligize. According to gtmetrix.com my TTFB is 1.4s: In my own testing, my TTFB was around ~1.3s. I am confused on why it's so high, even though I enabled Brotli, Caching (Static and Media files), Http3/Quic, I enabled html minifier, and I don't know why. My server is a 2GB CPU on Digital Ocean in NYC (close to where I am), so the location is not the problem. I have checked this stack overflow question, but removing the django-htmlmin package still had a high ttfb. My django view on this page is just: @minified_response def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) I think this is a simple query, and I don't expect the TTFB to be so high just for this get query. Is it a problem with my database (right now I am using sqlite)? If you need my any other file or thing to help me debug, just tell me. Also, according to this article by Cloudflare, my TTFB is high because At CloudFlare we make extensive … -
Getting Wrong answer in Put request in Django?
my models.py class QuestionModel(models.Model): question = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) doubt_class_id = models.ForeignKey(DoubtClasses, on_delete=models.CASCADE, null=True, blank=True) conceptual_class_id = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE, null=True, blank=True) mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) answer = models.TextField(default='', blank=True, null=True) my views.py class QuestionModelViewID(mixins.UpdateModelMixin,GenericAPIView): queryset = models.QuestionModel.objects.all() serializer_class = serializers.QuestionModel_serializer permission_classes = [IsAuthenticated] lookup_fields = ('type_of_class', 'pk') def get_queryset(self): print(self.kwargs['type_of_class']) type_of_class = self.kwargs['type_of_class'] if type_of_class == 'doubtclass': print('error here') return models.QuestionModel.objects.filter(id=self.kwargs['pk']) elif type_of_class == 'liveclass': return models.QuestionModel.objects.filter(id=self.kwargs['pk']) def put(self, request, type_of_class=None,pk=None): if int(request.data.get('author')) != self.request.user.id: return Response("you cannot edit othe user question", status=status.HTTP_405_METHOD_NOT_ALLOWED) try: question_id = models.QuestionModel.objects.filter(id=pk).first() if type_of_class =='doubtclass': class_id = question_id.doubt_class_id elif type_of_class == 'liveclass': class_id = question_id.conceptual_class_id except Exception as e: return Response(e) if request.user.is_superuser: #he can only update, delete, or add a new answer initial_answer_length = len(question_id.answer) #post a answer if initial_answer_length == 0: self.update(request, type_of_class, pk) if len(question_id.answer) == 0: return Response("please post an answer", status=status.HTTP_200_OK) class_id.doubtsAddressed += 1 class_id.save() return Response("Successfully posted answer", status=status.HTTP_200_OK) elif initial_answer_length != 0: #two cases are possible either update the answer or delete the answer self.update(request, type_of_class, pk) print(request.data.get('answer')) #answer is deleted print(len(question_id.answer)) if len(question_id.answer) == 0: class_id.doubtsAddressed -= 1 return Response("successfully deleted the answer", status=status.HTTP_204_NO_CONTENT) #answer is deleted else: return Response("successfully updated the answer", … -
Django ForeignKey.on_delete replace deleted object with a constant
Scenario: class A(models.Model): name = models.CharField(max_length=200) class B(models.Model): ref_to_A = models.ForeignKey(A, on_delete=models.CASCADE) <--- this part here Above scenario presents two models: A and B. B has a filed with reference to A instance. What I want is, on deleting this referenced instance of model A- to replace ref_to_A with it's name field. So that after deleting object field B.ref_to_A == A.name. None of the functions for on_delete (CASCADE/SET_NULL/SET_DEFAULT) seems like good starting point except models.SET() (https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.ForeignKey) which I don't understand from Django's docs example. This could be it, but can't think of a way to pass to this models.SET() function which will return a self.name from related object of model A. Another approach I've encountered searching for solution is to user signals, but after some research I can't really grasp how to start with this. This is important to me, because after deleting objects in db, I have to keep track to at least one specific field of related object. Thanks in advance! -
Django model filter by DateField not working
Trying to filter a Django model by DateField. But the filter does not work. Model.objects.filter(delivery_date=date) Where delivery_date is of type DateField and date is of type <class 'datetime.date'> -
Uknown command bash or /bin/bash on Docker Ubuntu:20.04 with docker-compose version 3.5
I am setting up docker with the Django application but the bash command is not working with docker Ubuntu:20.04 and docker-compose version 3.5. My docker version is Docker version 20.10.7, build f0df350 and docker-compose version is Docker Compose version 2.0.0-beta.4 Can anyone help me to resolve the issue? Below are my docker files: Dockerfile: FROM ubuntu:20.04 ENV PYTHONUNBUFFERED 1 RUN apt-get -y update RUN apt-get install -y --no-install-recommends default-libmysqlclient-dev RUN apt-get install -y gcc git libc-dev python3-dev python3-pip RUN ln -s /usr/bin/python3 /usr/bin/python RUN mkdir /app WORKDIR /app ADD . /app RUN pip install --upgrade pip && pip install -r requirements.txt EXPOSE 8000 ENTRYPOINT [ "/app/manage.py" ] docker-compose.yml version: '3.5' services: db: image: mysql:5.6 ports: - "3306:3306" environment: MYSQL_DATABASE: "mydb" MYSQL_ROOT_PASSWORD: "root" volumes: - mysql_data:/var/lib/mysql restart: always networks: default: aliases: - app-db django: build: . command: bash -c "while true; do runserver 0.0.0.0:8000; sleep 10; done" stdin_open: true tty: true volumes: - .:/app depends_on: - db ports: - "8000:8000" restart: always environment: MYSQL_DATABASE: "mydb" MYSQL_USER: "root" MYSQL_ROOT_PASSWORD: "root" MYSQL_HOST: "app-db" volumes: mysql_data: {} I am getting an error on command while running docker-compose up --build: bash -c "while true; do runserver 0.0.0.0:8000; sleep 10; done" Error: Unknown command: 'bash' Thanks … -
Django seems not to run on port 8000
I am working on a project linking django (for backend) and React (for frontend) It worked perfeclty for 5 months and then this morning, when I run django (python manage.py runserver), I cannot access to the django server. First, my frontend tells me he can't have an access to it: Proxy error: Could not proxy request /api/token/refresh/ from localhost:3000 to http://localhost:8000/. See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED). Then I try to type 127.0.0.1:8000 in my browser's navbar, in order to access the django admin (as I used to do, until this morning) and my browser tells me that localhost refuses connection. Finally, I typed netstat -aon | find /i "listening" in my cmd and the list did not include port 8000 I don't know what to do and when I type "django does not run on port 8000" on the Internet, I cannot find a satisfying answer. Could someone help me? -
Django multiple app connect to multiple DB(sqlite)
I have two Django apps, each with one models.py. I'd like to connect the db to each app, what should I do? -
Why does celery works with "--concurrency 1 -P solo" and not without?
When I use : celery -A FAM worker -l info --concurrency 1 -P solo I can run my tasks from celery. when I use : celery -A FAM worker -l info It doesn't work. But I cannot understand why. I see there is a difference : "16 (prefork)" vs "1 (solo)". What is the difference ? And why does the solo works and the other does not ? -
Translate only specific views
In my webapp there's the concepto of associations/organizations, modelled by Association. A good number of views can be grouped under the umbrella of an organization. You can define a default language for your association: class Association(models.Model): language = models.CharField(max_length=3, null=True, blank=True, verbose_name=_('Default Language')) We would want these views to be shown in the association's default language rather than the user preference language. I tried with a decorator: def association_language(force_language=False): def wrapper(func): @functools.wraps(func) def decorator(request, *args, **kwargs): try: association = get_object_or_404(Association, pk=kwargs['pk']) language = association.language if language and check_for_language(language): cur_language = translation.get_language() translation.activate(language) response = func(request, *args, **kwargs) # option for certain views to override the user language preference if force_language: request.session[LANGUAGE_SESSION_KEY] = language else: translation.activate(cur_language) return response except KeyError: pass return func(request, *args, **kwargs) return decorator return wrapper Which should be attached to those views, like: class AssociationUpdateView(UpdateView): @method_decorator(association_language(force_language=True)) def dispatch(self, request, *args, **kwargs): return super(AssociationUpdateView, self).dispatch(request, *args, **kwargs) However this is not working at all. Unless I remove the translation.activate(cur_language) line. It seems even though the response is produced before switching back to the original language, the response is in that language anyway. What am I doing wrong here? -
Django get query execution time
Is there a way to measure Django query time without using django-debug-toolbar? It is not for debugging/logging, I need it to display on the webpage like about # results (# seconds). -
Django Rest Framework API Creating a Video model so that I can use React.js as FrontEnd
I've been trying to create a social media app that has users that can upload both post and Videos that people can watch. I am using Django Rest Framework as API, but the problem is Im running into a blockade because I can't seem to under How the package Django-video-app works or How I can have a model for videos with a serializer and view that can make it easy for me to have users be able to upload video files so that other users can watch. I really want to use react.js as a frontend so If there's anyone who is way more experienced that me that can do this, I would love it if someone can walk me through this process. I've been searching the internet for walkthroughs but I have not gotten lucky. I've read the documentation for Django-video-app package, but that didn't help and there's nothing on Django Rest Framework docs that are useful. Please help me -
Override the IsAuthenticated permission class with one that checks firebase
I am using firebase(pyrebase library) for my authentication with a django backend and a react frontend.For this to work I had to override the DRF auth class TokenAuthentication with my FirebaseAuthentication. But I still get 401 unauthorised when I try to access a view since I also need to override the drf permission class isAuthenticated.But I have been searching for a way to do this with python without success.Any help would be appreciated. Below is a snippet of the permission class and where its applied on my views DRF permissions.py class IsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): return bool(request.user and request.user.is_authenticated) views.py class FinanceTransactionList(GenericAPIView): authentication_classes = [FirebaseAuthentication] permission_classes = [IsAuthenticated] @classmethod @encryption_check def post(self, request, *args, **kwargs): ... -
QuerySet' object has no attribute 'save'
I'm getting this error when trying to get the image attribute and set some values according to the content of service_name attribute, both service_name and image_url are attributes of the same model, but I want to set the image according to the content service_name using condition statements. Any help or other way of doing it is highly appreciated Here is the models module: class JobServices(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) service_name = models.CharField(max_length=100, default="nom du service") hour = models.IntegerField(default="Heures") amount = models.FloatField(default="Cout") service_date = models.DateTimeField(auto_now_add=True, null=True) description = models.CharField(max_length=2000, null=True, default="annonce") image_url = models.CharField(max_length=2000, null=True, blank=True) image = models.ImageField() And here is the view module def taches(request): taches = JobServices.objects.all() if request.user.is_authenticated: service_name = request.POST.get('service_name') image_url = request.POST.get('image_url') if service_name == 'don du sang': image_url = 'https://images.pexels.com/photos/4226902/pexels-photo-4226902.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' taches.save() elif service_name == 'cours de soutien': image_url = 'https://images.pexels.com/photos/1181529/pexels-photo-1181529.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' taches.save() elif service_name == 'jardinage': image_url = 'https://images.pexels.com/photos/4505166/pexels-photo-4505166.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' taches.save() elif service_name == 'reparation': image_url = 'https://www.pexels.com/photo/gray-scale-photo-of-gears-159298/' taches.save() else: image_url = 'https://images.pexels.com/photos/8080823/pexels-photo-8080823.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' taches.save() return render(request, 'taches.html', {'taches': taches}) else: return redirect('login') -
AllowAny CreateAPIView returns 401 for unauthenticated users
I use DRF with djangorestframework-simplejwt package. In my settings.py: INSTALLED_APPS = [ ... 'rest_framework', ... ] ... REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication', ), } SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header', 'description': 'E.g. \'Bearer jwt.token.here\'' } } } And in my apps' views.py: ... class PublicCreateView(generics.CreateAPIView): """ Should be available for unauthenticated users """ serializer_class = PublicThingSerializer def post(self, request, *args, **kwargs): return Response("It works!", 200) ... Yet for some reason this view returns 401 response for unauthenticated users. I tried a lot of things, the best I got was noticing that when I remove the REST_FRAMEWORK config from my settings.py completely, the response code changes to 403 forbidden. Any ideas? -
I am trying to load a modified pdf through the response of an ajax call. But always getting 404 error in Django python
I am very new to Django and infact its my first project using Django. My HTML page "verify.html" is containing a pdf inside an iframe in the right side and in the left side there are input tags with values. Onclick on any of these input tags loadDoc() javascript call is fired and through ajax call I am calling a python function to highlight some text and save that highlighted pdf in url: "static_ocr/invoices/Grger - Invoice_high.pdf". The pdf file is properly modified and saved in the specified location but with the response when I am trying to load the pdf, I am getting a 404 error: "GET /verify/static_ocr/invoices/Grger - Invoice_high.pdf HTTP/1.1" 404 4298 urls.py path('verify/', views.map_invoice, name='verify'), path('verify/highlight/', views.highlight, name='highlight'), views.py def map_invoice is rendering verify.html page def highlight is for highlighting the pdf and storing the same. verify.html function loadDoc(){ ------------ $.ajax({ type: "POST", url: '{{ 'highlight/' }}', data: {csrfmiddlewaretoken: '{{ csrf_token }}', text: val}, success: function(response){ alert(response); $("#pdfview").attr("src", "static_ocr/invoices/Grger - Invoice_high.pdf"); <iframe id="pdfview" src="{% static pdf_url %}" width="85%" height="750px"></iframe> Pdf is highlighted and stored but not getting displayed with error: "GET /verify/static_ocr/invoices/Grger - Invoice_high.pdf HTTP/1.1" 404 4298 Thanks in advance. -
'No active account found with those credentials' when trying to log in with Django REST + Simple JWT
I'm trying to set up this API with user authentication but I keep getting the error message in the title when trying to log in. Registration seems to work and the super user can log in. I believe it is due to the password hashing, because when I go to the admin panel, every user has the same message: 'Invalid password format or unknown hashing algorithm.' except the super user (which I created in the terminal). Have I made a mistake in the user creation part? Serializers.py from rest_framework import serializers from rest_framework.permissions import IsAuthenticated from django.db import models from django.contrib.auth.models import User from django.contrib.auth import authenticate from django.contrib.auth.hashers import make_password class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' def validate(self, data): user = authenticate(**data) if user and user.is_active: return user Views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework import generics, permissions, mixins from django.contrib.auth.models import User from .serializers import RegisterSerializer class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "message": "User created successfully!" }) … -
How to load the defualt value in combo box and how can add product to the cart without reloading the page in django?
Problem I want to the following things but am unable to understand that how can I do the following things. Firstly, I want that when the page is loaded the defualt values should be displayed from using the value from the combox. For example pack of 1KG is the defualt value so it's price and other values should be updated when the page is loaded. Secondly, I want that when the product is added to the cart the page is not reloaded or refreshed and a popup is shown that the product is added to the cart. CODE Script $(document).on("change", '.tranactionID', function (event) { event.preventDefault(); //get closest outer div.. var selector = $(this).closest(".productID") //find to get required elements.. selector.find('.id_price').text($(this).children(":selected").attr("price")); selector.find('.price-sale').text($(this).children(":selected").attr("sale_price")); selector.find('.id_discount').text($(this).children(":selected").attr("discount")); let id = $(this).find("option:selected").attr('transID'); let Url = `{% url 'cart:cart_add' 0 %}`.replace(0, id); selector.find("form").attr('action', Url); }); HTML {% regroup transaction by productID as ProductList %} {% for productID in ProductList %} <div class="col-sm-3 productID" > <div class="product"> <a href="{% url 'main:product-detail' productID.grouper.id %}" class="img-prod"><img class="img-fluid" src={{productID.grouper.product_image.url}} alt="" height="200px"> <span class="status id_discount">%</span> <div class="overlay"></div> </a> <div class="text py-3 pb-4 px-3 text-center"> <h3><a href="#">{{productID.grouper}}</a></h3> <div class="d-flex"> <div class="pricing"> <p class="price"><span class="mr-2 price-dc id_price">Rs. </span><span class="price-sale">Rs. </span></p> </div> </div> <select class="tranactionID" id="ItemID" … -
I cant access the files I upload with django inside the website with nginx when I try to download them
In my python Django project I can't figure out how to download .pdf files with nginx. In the site there will be constant uploads from an admin an the site shows the download links for this button in html and I direct to download with href. I tried to define a dynamic location in nginx locations but it just gives me a "404 not found" or " the requested resource was not found on this server.". I checked that files exists at the correct path but nginx still does not work. Nginx Location File : server { listen 80; server_name 134.209.252.222; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/mjr/hedefcekilis/mysite; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /static/admin { root /home/mjr/hedefcekilis/cekilisenv/lib/python3.8/site-packages/django/contrib/admin; } location ~ \.(pdf) { root /home/mjr/hedefcekilis/mysite/media/ibra/~; } } The pdf files are in different folders in the "ibra" folder. And these folder names change over time. How can I solve this problem? -
Training Deep Learning Model using Django
I am trying to train Deep Learning Model using Django. I faced OSError: Cannot understand given URI: False error. Anyone who solved this problem, please help me. -
django error: was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)
I'm creating a django project. Everything was fine and I had no problem with loading fontawesome files. But now it can not show the fontawesome icons and in the console there are some errors: Recently, I've made some changes somewhere, and didn't attention when these errors occur and when fontawesome icons start not showing. But I'm sure the changes where not in fontawesome files or where I link to those files. So What has happend? And this is the result when I used curl -I the-path: ╰─$ curl -I http://localhost:8000/blog/static/blog/fontawesome/css/fontawesome.css HTTP/1.1 404 Not Found Date: Wed, 30 Jun 2021 08:35:31 GMT Server: WSGIServer/0.2 CPython/3.9.2 Content-Type: text/html X-Frame-Options: DENY Content-Length: 3376 X-Content-Type-Options: nosniff Referrer-Policy: same-origin And this is where I link to the css files: -
Improving API Performance in DRF with select_related and prefetch_related
the below serializer and view which I am using to get data from multiple models is taking around 4 secs to get data. I have added select_related and prefetch_related and still the num of queries are around 16. I am not sure what else can be down to make sure the api is faster. class WalletTransactionsSerializer(serializers.Serializer): id= serializers.IntegerField(read_only=True) transaction_date= serializers.DateTimeField(read_only=True) student_transaction= StudentsTransactionSerializer(many=True,read_only=True) staff_transaction= StaffPartnerSerializer(many=True,read_only=True) transaction_amount= serializers.DecimalField(max_digits=12, decimal_places=2,read_only=True) closing_balance= serializers.DecimalField(max_digits=12, decimal_places=2,read_only=True) remarks=serializers.CharField(read_only=True) updated_on=serializers.DateTimeField(read_only=True) transaction_status=serializers.CharField(read_only=True) refund_transaction= RefundTransactionsSerializer(many=True,read_only=True) wallet=WalletPartialSerializer(read_only=True) razorpay_info=RazorpaySerializer(many=True,read_only=True) class Meta: model=WalletTransactions fields=['id','transaction_date','transaction_amount','closing_balance','remarks','updated_on','transaction_status','staff_transaction','student_transaction','refund_transaction','wallet','razorpay_info'] @staticmethod def setup_eager_loading(queryset): """ Perform necessary eager loading of data. """ queryset= queryset.select_related('wallet','wallet__user') queryset= queryset.prefetch_related('refund_transaction') queryset= queryset.prefetch_related('staff_transaction__wallet_transaction_id') queryset=queryset.prefetch_related('student_transaction__student_id','student_transaction__application_id','student_transaction__course_id','student_transaction__university_id','student_transaction__promocodeid') queryset= queryset.prefetch_related('razorpay_info','razorpay_info__wallet_transaction_id') return queryset #view def transaction_search(request): user_id = request.GET.get('user_id') user_role= request.GET.get('role') transactions= WalletTransactions.objects.all().distinct() if (user_id and user_role) and str(user_role)=='abc': transactions = WalletTransactions.objects.filter(wallet__user=str(user_id)).distinct() # print("data is",transactions) if (user_id and user_role) and str(user_role)=='def': transactions = WalletTransactions.objects.all().distinct() # print(transactions) return transactions.distinct() class TransactionsViewSet(viewsets.ModelViewSet): serializer_class=WalletTransactionsSerializer pagination_class=StandardResultsSetPagination filter_backends=(filters.DjangoFilterBackend,) filterset_class = TransactionsFilter def get_queryset(self): transactions = transaction_search(self.request) transactions= self.get_serializer_class().setup_eager_loading(transactions) return transactions def dispatch(self, *args, **kwargs): response = super().dispatch(*args, **kwargs) # For debugging purposes only. from django.db import connection print('# of Queries: {}'.format(len(connection.queries))) print('Queries: {}'.format(connection.queries)) # print("Query",connection.queries) return response -
How to properly kill MySQL/ MariaDB connections in Django using custom connectors
I am currently working on a project and I use the MariaDB connector to run the queries. I can't use ORM so I have to use raw queries. In general, the system works fine, as expected, but when I make a bit 'big' queries I get a Too many connections error message. This has happened to me for both MySQL and MariaDB connectors, but I mainly use MariaDB. Example of my code (truncated / simplified): import mariadb def get_cursor(): conn = mariadb.connect( user="user", password="pass", host="localhost", database="db") return conn, conn.cursor(named_tuple=True) def get_duplicated_variants(): results = [] conn_cursor = get_cursor() cursor = conn_cursor[1] conn = conn_cursor[0] try: cursor.execute("SELECT * FROM `db`.s_data;") columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) cursor.close() conn.close() return results except mariadb.Error as e: print(f"Error: {e}") What I've tried: show status like '%onn%'; And also: show variables like 'max_connections'; So the max_used_connections = 152 and I have 2503 Connections. I also tried to execute the following query: SELECT CONCAT('KILL ', id, ';') FROM INFORMATION_SCHEMA.PROCESSLIST WHERE `User` = 'user' AND `Host` = 'localhost' AND `db` = 'db'; As seen in this question. But the number of connections is the same after running the … -
how to make a message model in Django where you can choose more than one person as the recipient
So, I'm trying to make a messaging model(between users) in Django admin where the sender can choose more than one recipient for the message. Models.py: class Message(models.Model): body = models.TextField(verbose_name=") sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,editable=False) recipient = models.ManyToManyField(settings.AUTH_USER_MODEL) admin.py: class MessageAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs sender_query = qs.filter(sender=request.user) recipient_query = qs.filter(recipient=request.user) return sender_query | recipient_query My current approach is the code above using a ManyToManyField. But this has created two bugs: The sender will see the same message more than once if more than one recipient are chosen, for example if the sender chooses three recipients, he will have three of the same message in his queryset The sender will not be able to open the message he has sent(if more than one recipient are chosen) because this error will get raised:get() returned more than one Message -- it returned 2!. of course the "2" can be any other number The thing I can't figure out Is that these bugs won't produce if the sender is superuser(And I assume that means there is a problem with my get_queryset code) What am I doing wrong in here? P.S: the reason of sender field being … -
Getting logic error while making put request in Django rest framework
my model class QuestionModel(models.Model): question = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) doubt_class_id = models.ForeignKey(DoubtClasses, on_delete=models.CASCADE, null=True, blank=True) conceptual_class_id = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE, null=True, blank=True) mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) answer = models.TextField(default='') I have created a answer field to only superuser editable by using question admin class QuestionAdmin(admin.ModelAdmin): readonly_fields = ['answer'] def get_readonly_fields(self, request, obj=None): if request.user.is_superuser: return [] else: return self.readonly_fields admin.site.register(QuestionModel, QuestionAdmin) my views.py def put(self, request, type_of_class=None,pk=None): if int(request.data.get('author')) != self.request.user.id: return Response("you cannot edit othe user question", status=status.HTTP_405_METHOD_NOT_ALLOWED) if pk: question_id = models.QuestionModel.objects.filter(id=pk).first() #if answer originally exists if len(question_id.answer) > 0: self.update(request, type_of_class, pk) #this means answer is just updated if len(question_id.answer) > 0 : return Response("Successfully updated answer", status=status.HTTP_200_OK) # this means that answer is deleted so decrease doubt address count else: if type_of_class =='doubtclass': class_id = question_id.doubt_class_id elif type_of_class == 'liveclass': class_id = question_id.conceptual_class_id class_id.doubtsAddressed -= 1 class_id.save() return Response("Successfully deleted answer", status=status.HTTP_200_OK) #if answer is not originally there self.update(request, type_of_class, pk) #this means that a student has updated his answer if question_id.answer == '': return Response("successfully updated a question", status=status.HTTP_200_OK) #this means that a mentor has posted a answer if type_of_class =='doubtclass': print("type_of_class =='doubtclass'") class_id = question_id.doubt_class_id elif type_of_class == 'liveclass': print("type_of_class =='conceptual_class'") …