Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to overcome "Object of type date is not JSON serializable"?
I am building a booking system, currently i am trying to have unavailable dates displayed in red on a jQuery datepicker. I have composed a view that gets the unavailable dates and saves this to an array. When trying to parse into JavaScript I am getting the following error: "Object of type date is not JSON serializable". I have seen this answered on here, however the solutions I have tried do not seem to be working. In particular I have tried the answers given here: How to overcome "datetime.datetime not JSON serializable"? def unavailable_dates(): confirmed_bookings = Booking.objects.filter(booking_status=1) bookings_max_attendees = confirmed_bookings.values( 'booking_date', 'booking_time').annotate( attendees=Sum('number_attending')).filter(attendees=20) unavailable_dates = [] for booking in bookings_max_attendees: unavailable_dates.append(booking['booking_date']) return unavailable_dates # https://stackoverflow.com/questions/77218397/how-to-access-instances-of-models-in-view-in-order-to-save-both-forms-at-once?noredirect=1&lq=1 def customer_booking(request): if request.method == 'POST': customer_form = CustomerForm(request.POST, prefix='customer') booking_form = BookingForm(request.POST, prefix='booking') if customer_form.is_valid() and booking_form.is_valid(): customer = customer_form.save(commit=False) customer.user = request.user customer.save() booking = booking_form.save(commit=False) booking.customer = customer if limit_no_attendees(booking.booking_date, booking.booking_time, booking.number_attending): booking.save() customer_form = CustomerForm() booking_form = BookingForm() messages.add_message(request, messages.SUCCESS, 'Your booking request was successful, please visit your profile to view the status!') else: messages.add_message(request, messages.ERROR, 'Date and time unavailable!') else: customer_form = CustomerForm(prefix='customer') booking_form = BookingForm(prefix='booking') unavailable_booking_dates = unavailable_dates() dataJSON = json.dumps(unavailable_booking_dates) context = { 'customer_form': customer_form, 'booking_form': booking_form, 'data': … -
has_object_permission method doesn't work Django REST Framework
I want to check in my ModelViewSet if user can create the invitation for the other user to his company. I have 4 models: # Abstract model TimeStampedModel class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: # abstract = True to enable models inherit from TimeStampedModel abstract = True # Custom User model class User(AbstractUser, TimeStampedModel): # Make these fields not to be null email = models.EmailField(unique=True, null=False, blank=False) first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) image_path = models.ImageField(upload_to='img', default='profile-pic.webp') # Assing base user manager for admin panel objects = CustomUserManager() USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] # Create your models here. class Company(TimeStampedModel): VISIBILITY_CHOICES = ( ('hidden', 'Hidden'), ('visible', 'Visible for all'), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=False, null=False, unique=True) description = models.TextField(blank=False, null=False) visibility = models.CharField(max_length=15, choices=VISIBILITY_CHOICES, default='visible') class Meta: verbose_name = "Company" verbose_name_plural = 'Companies' # Plural naming def __str__(self): return self.name # Interactions between users and companies class CompaniesUsers(TimeStampedModel): STATUS_CHOICES = ( ('pending', 'Pending'), ('accepted', 'Accepted'), ('revoked', 'Revoked'), ('rejected', 'Rejected'), ) company = models.ForeignKey(Company, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(default='pending', choices=STATUS_CHOICES) def __str__(self): return f"{self.company} - {self.user} - {self.status}" I created the custom permission … -
Pytest causes 'invalid object name' error while setting up test databases
I'm trying to use Pytest to run unit tests on a Django application, but I'm having trouble interacting with Django's database models. A majority of the models in my application have the managed=False value set, since they're connected to external DBs. I'm using a script that sets the them to managed=True when running the test, because I was having issues with the test DBs being created without any contents. The problem is that whenever I run a test that needs DB access and the system starts creating test databases, it throws an error as soon as it hits one of the tables whose model has been changed to managed=True. Looking at the verbose traceback from Pytest, it seems like the system is trying to query the test database for the entire content of the table in question, and failing because the table doesn't exist. This only happens when one or more models for external have been changed to managed=True, either manually or using the script mentioned earlier. If I don't change any of the models, the test DB creation process works without errors, but the resulting test DBs don't contain any tables. The one model in the application which does … -
Dynamically customize django admin columns in model view
Follow up to this quetsion: Dynamically customize django admin columns? How to do it with django 4.2 lib django-xadmin doesnt work with django 4.2 This model for example `class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") choice_text = models.CharField(max_length=200, default='choice') votes = models.IntegerField(default=0)` and admin page `class QuestionAdmin(admin.ModelAdmin): list_display = ['question_text', 'pub_date', 'choice_text', 'votes'] admin.site.register(Question, QuestionAdmin)` -
Nginx not passing response body from Server 1 to Server 2 when 401 status code with new access token is returned
Question: I'm currently working on a ReactJS application that interacts with multiple backends, including an authentication server using Node.js, another backend using Node.js, and a Django server. Nginx is used to manage requests and distribute them between the front end and these backends. The problem I'm facing arises when I call a backend with an expired access token. In such cases, the authentication server regenerates a new access token and sends it back to the front end. The front end should then make a new request to the same API with this new access token. The challenge lies in how Nginx handles the response from Server 1 (authentication with Node.js) when it is called indirectly from Server 2 (Django). When Server 1 returns a 401 status code along with a new access token in the response body, Nginx doesn't pass this response body to Server 2 or, subsequently, to the frontend. Here's a detailed breakdown of the scenario that doesn't work as expected: Scenario 1 (Problematic): Frontend call to Server 2 (Django) via Nginx, but it has to pass through Server 1 (authentication with Node.js) to check the access token first: Front end calls Server 2 via NGINX. NGINX redirects … -
why can't django return a plain text response with a link to download the file?
I have in Django eksport functionality, in the custom admin. So, when requesting to get everything from the database, I make an ORM query of the necessary sample - the query is heavy, but it works fine, I get the data at once, no more trips to the database. Then comes the functionality of working with this data, shoved everywhere there, processed, and finally shoved into the dataframe pandas and written to a CSV file, and saved in the directory (before that immediately tried to give the user), the file weighs about 280mb. So, what is the actual problem, the real file is saved quickly relatively, but the response to the user can come from half an hour, just with a link to download the file. def save_data_in_csv_file(df_jewelry): """write data Attributes: - df_jewelry: data frame pandas +- 1_300_000 rows. """ download_folder = os.path.join(os.path.dirname(__file__), 'download_file') if not os.path.exists(download_folder): os.makedirs(download_folder) file_path = os.path.join(download_folder, 'output.csv') with open(file_path, 'wb') as file: df_jewelry.to_csv(file, index=False) download_link = ( 'path_to_file' ) response_data = { 'message': 'File save!', 'download_link': download_link, } response = Response(response_data, status=201) return response This is a view, it runs the main script, and from the code above it just gets the response, and just … -
Deserialization/Serialization DRF
I am interested in understanding which pattern of the below is more aligned with the SOLID principles. Say We have a class CreateView(generics.CreateAPIView) in DRF. Option 1: Single Serializer for serialization/deserialization from rest_framework import serializers class MySerializer(serializers.Serializer): field1 = serializers.CharField()) def to_representation(self, instance): return { 'field1': instance.field1, } Option 2: Create 2 classes MySerializer ( serialize the response I want to create and pass to the response.data ) MyDeserializer ( deserialise my data / perform sanitisation/validation of the incoming request.data ) -
issue with deploying django application with gunicorn, supervisorctl
I'm deploying django application using gunicorn, supervisorctl and nginx but I'm getting the below error in nginx log file 172.69.178.94 - - [12/Oct/2023:11:18:52 +0000] "POST /api/notify/send-notification HTTP/1.1" 502 166 "-" "PostmanRuntime/7.33.0" 2023/10/12 11:24:05 [crit] 551667#551667: *1 connect() to unix:/home/pankaj/cn_notification/cn_notification/cn_notify.sock failed (13: Permission denied) while connecting to upstream, client: 172.69.178.95, server: notify.codingnap.com, request: "POST /api/notify/send-notification HTTP/1.1", upstream: "http://unix:/home/pankaj/cn_notification/cn_notification/cn_notify.sock:/api/notify/send-notification", host: "notify.codingnap.com" 172.69.178.95 - - [12/Oct/2023:11:24:05 +0000] "POST /api/notify/send-notification HTTP/1.1" 502 166 "-" "PostmanRuntime/7.33.0" My supervisor config file [program:cn_notify] directory=/home/pankaj/cn_notification/cn_notification command=/home/pankaj/cn_notification/notify-venv/bin/gunicorn --workers 1 --bind unix:/home/pankaj/cn_notification/cn_notification/cn_notify.sock cn_notify.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/cn_notify.log stdout_logfile=/var/log/cn_notify.log user=pankaj group=www-data [group:guni] programs:cn_notify and nginx config file server { listen 80; server_name notify.codingnap.com; error_log /var/log/nginx/cn_notify_log; access_log /var/log/nginx/cn_notify_log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/pankaj/cn_notification/cn_notification; } location / { include proxy_params; proxy_pass http://unix:/home/pankaj/cn_notification/cn_notification/cn_notify.sock; } } What could be the possible way to solve this issue 🙂 -
How can I deploy the django web application on apache in windows?
I want to deply the django web application on apache in windows. Howw can I do that step by step? I have installed python and apache on windows. How can I config the apache to serve django web app? I deploy django web app on local host with out apache but i know that its not secure to server users on the web without web server. -
Permission class method def has_object_permission is not called
The problem is any user is able to delete the comment created by the other user, even i created and added the custom permission.py file, i also checked that def has_object_permission method is not running i tried to print "print statement" on terminal. I want that only owner of comment can delete it's own comment and owner of the Post can delete anyone's comment. my view: class CommentPostApiView(generics.ListCreateAPIView, generics.DestroyAPIView,generics.GenericAPIView): serializer_class = serializers.CommentPostSerializer authentication_classes = (TokenAuthentication,) permission_classes = [IsAuthenticated, IsCommentOwnerOrPostOwner] def get_queryset(self): post_id = self.kwargs.get('post_id') return models.CommentPost.objects.filter(post__pk=post_id, reply_to_comment__isnull=True) @transaction.atomic def create(self, request, *args, **kwargs): post_id = self.kwargs.get('post_id') parent_comment_id = self.kwargs.get('parent_comment_id') user = self.request.user content = request.data.get('content') try: post = models.PicPost.objects.select_for_update().get(pk=post_id) if parent_comment_id is not None: reply_to_comment = models.CommentPost.objects.select_for_update().get(pk=parent_comment_id) comment_post = models.CommentPost(post=post, commenter=user, content=content, reply_to_comment=reply_to_comment) else: comment_post = models.CommentPost(post=post, commenter=user, content=content) comment_post.save() models.PicPost.objects.filter(pk=post_id).update(comments_count=F('comments_count')+1) except models.PicPost.DoesNotExist: raise ValidationError("Post does not exist.") except models.CommentPost.DoesNotExist: raise ValidationError("Parent comment does not exist.") return Response({"detail": "Comment added successfully."}, status=status.HTTP_201_CREATED) @transaction.atomic def destroy(self, request, *args, **kwargs): comment_id = self.kwargs.get('parent_comment_id') try: comment = models.CommentPost.objects.select_for_update().get(pk=comment_id) post_id = comment.post.id comment.delete() models.PicPost.objects.filter(pk=post_id).update(comments_count=F('comments_count')-1) except models.CommentPost.DoesNotExist: raise ValidationError("This comment does not exists") return Response({"detail": "Comment deleted successfully."}, status=status.HTTP_201_CREATED) **Custom Permission file** class IsCommentOwnerOrPostOwner(permissions.BasePermission): """Allow owners of comment, reply or post to delete them""" def … -
Django REST Framework, write an API that allows any user to upload an image in jpg or png
It should be possible to easily run the project. docker-compose is a plus users should be able to upload images via HTTP request users should be able to list their images there are three builtin account tiers: Basic, Premium and Enterprise: users that have "Basic" plan after uploading an image get: a link to a thumbnail that's 200px in height users that have "Premium" plan get: a link to a thumbnail that's 200px in height a link to a thumbnail that's 400px in height a link to the originally uploaded image users that have "Enterprise" plan get a link to a thumbnail that's 200px in height a link to a thumbnail that's 400px in height a link to the originally uploaded image How can I create those accounts? I've done just users and they can upload images. -
SMTP Authentication error with Gmail and Django
I have been facing an issue for a while now. I need my Django app to send password reset emails to users whenever they request for it. I have configured the SMTP correctly and even tested the connection using GMass and it seems to work fine. However, it does not work on my Django app. I have enabled 2FA and I'm using an App Password. This is the error that it throws at me. SMTPAuthenticationError at /reset_password/ `(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials z7-20020a7bc7c7000000b003fee567235bsm21423680wmk.1 - gsmtp') Request Method:POSTRequest URL:http://127.0.0.1:8000/reset_password/Django Version:4.2.5Exception Type:SMTPAuthenticationErrorException Value:(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials z7-20020a7bc7c7000000b003fee567235bsm21423680wmk.1 - gsmtp')Exception Location:C:\Users\perfa\AppData\Local\Programs\Python\Python311\Lib\smtplib.py, line 662, in authRaised during:django.contrib.auth.views.PasswordResetViewPython Executable:C:\Users\perfa\AppData\Local\Programs\Python\Python311\python.exePython Version:3.11.5Python Path:['F:\\Python Learning\\Projects\\crm', 'C:\\Users\\perfa\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\perfa\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\perfa\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\perfa\\AppData\\Local\\Programs\\Python\\Python311', 'C:\\Users\\perfa\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages']Server time:Thu, 12 Oct 2023 09:52:40 +0000 Here is my SMTP config ` `#SMTP Configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'pe#######@gmail.com' EMAIL_HOST_PASSWORD = 'm############'` Sorry I had to hide my email and password for security reasons. I have tried testing the SMTP configs on GMASS and it worked but the same configs do not work on my code. If the configuration works on my code, I expect … -
What is the simplest way to handle django ORM access e.g <model>__<model>, select_related
I want to implement a soft delete to model. The problem is that project is big and i need to find all filtering and access expressions to target model and edit it. Is there a workaround to handle them on target model side? -
Django - struggling with excessive queries
I need to implement a website menu where every root item can have a dropdown with some more items, and I need to do that using some django models and without any third party tools like mptt. So it will be a tag. So here are the models: class Menu(models.Model): name = models.CharField(max_length=150) class MenuElement(models.Model): name = models.CharField(max_length=100) menu = models.ForeignKey('Menu', on_delete=models.CASCADE) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') And here is the function that's supposed to do the trick: def draw_menu(menu_name): menu_elements = MenuElement.objects.filter(menu__name=menu_name).select_related('parent') for element in menu_elements: if not element.parent: element.children_list = element.children.all() And here comes the problem. If I get a list of all children of a menu element, it's super easy to display the thing on the web page. But if I leave it like this, there will be an additional query for every root element (to get the children), so 10 elements = 10 queries. And select related cannot really help in here, at least I don't see how to utilize it. 10 queries for a menu is not an option, even 2 is too much, is it possible to do the whole thing using one? Maybe if I redesign the model somehow? -
django-debug-toolbar configure INTERNAL_IPS for docker, compatible ip6
I just got django-debug-toolbar to work in Docker, but with a bit of a hack. The official instructions say if DEBUG: import socket # only if you haven't already imported this hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips] + ["127.0.0.1", "10.0.2.2"] However I saw no toolbar. In my template html I printed {{request.META.REMOTE_ADDR}} and noticed that it was an IP6 address. So I changed the above INTERNAL_IPS logic to if DEBUG: hostname, _, ips = socket.gethostbyname_ex (socket.gethostname()) ips = [ip[:ip.rfind(".")] + ".1" for ip in ips] INTERNAL_IPS += ips INTERNAL_IPS += ['::ffff:'+ip for ip in ips] This works but it feels hacky. Is there a better way to do this? -
find alternative to celery-beat to run slow tasks
I have a problem with a celery task that I have to run every 30 seconds. The task consists of connecting through ModbusTCP to a system to read some values. The problem is that I have to read these values from several systems and in 30s it is not able to finish the execution of all of them. As at the moment I do it is through celery-beat I execute a task that consists of a loop that goes through all the systems to which I have to connect to read the data. The connection attempt sometimes takes a while and that is what causes that in 30 seconds I don't have time to execute the whole loop. Is there any alternative to celery-beat that can fit the functionality I am looking for? Thanks! Try to find a solution for the problem or any alternative to solve my situation -
Django REST Framework Viewset Executes Actions Multiple Times and Shows 'None' for GET Requests
I have a Django REST framework viewset with multiple actions such as list, create, and more. When I send a GET request, I noticed that some actions are executed multiple times, and the action is sometimes set to "None." Can anyone help me understand why this is happening and how to resolve it? Here is my view code for reference: Url : path( "question/questionnaire/<int:questionnaire_id>/", QuestionModelViewSet.as_view({"get": "list", "post": "create"}), name="question_R", ), path( "question/<int:pk>/", QuestionModelViewSet.as_view( { "get": "retrieve", "delete": "destroy", "patch": "partial_update", "put": "update", } ), name="question_URD", ), permission : class IsStaffDoctorOrIsStaffHumanResource(permissions.BasePermission): def has_permission(self, request, view): # Check if the user belongs to the "staff_human_resource" group return request.user.groups.filter(name="staff_doctor").exists() or request.user.groups.filter(name="staff_human_resource").exists() View : class QuestionModelViewSet(viewsets.ModelViewSet): pagination_class = LargePagination def get_permissions(self): if self.action == "retrieve" or self.action == "list": permission_classes = [IsStaffDoctorOrIsStaffHumanResource] else: permission_classes = [DjangoModelPermissions] return [permission() for permission in permission_classes] def get_queryset(self): print(self.action) if self.action == "retrieve" or self.action == "update" or self.action == "partial_update" or self.action == "delete" or self.action == None : pk = self.kwargs.get("pk") data = Question.objects.filter(pk=pk) return data if self.action == "list" or self.action == "create": questionnaire_id = self.kwargs.get("questionnaire_id") data = Question.objects.filter(questionnaire=questionnaire_id) return data else: pk = self.kwargs.get("pk") data = Question.objects.filter(pk=pk) return data def get_serializer_class(self): if self.action == … -
what is local variable 'post' referenced before assignment?
I am making a blog with Django and it keeps showing this error to me while I followed the tutorial correctly and the person I am using his tutorial is not getting the same error where did I go wrong? plus some of the code like "post" and "request" are gray why?? Thanks in advance from django.shortcuts import render, redirect, get_object_or_404 from .forms import postform from .models import post # Create your views here. def detail(request, id): post = get_object_or_404(post, pk=id) return render(request, "posts/detail.html", {"post": post }) def delete(request, id): post = get_object_or_404(post, pk=id) post.delete() return redirect("/") def new(request): if request.method == "POST": form = postform(request.POST) if form.is_valid(): form.save() return redirect("/") else: form = postform() return render(request, "posts/new.html", {"form": form }) -
sorl thumbnail with cloudinary remote storage
Can't seem to find any info regarding using sorl.thumbnail with cloudinary. I managed to make it kinda work, but it generates thumbs on each reload which is obviously not right. For the information, I use cloudinary for media files only. -
Филтр данных для экспорта в excel [closed]
я вкрутил кнопку сохранения в экзел из базы данных. теперь нужно чтобы эта кнопка принимала все фильтры применённые в dashboard в теге table вот html представления <table class="table table-hover table-bordered"> <thead class="table-light"> <tr> <th scope="col"> ID </th> <th scope="col"> Адресс размещения </th> <th scope="col"> Тип </th> <th scope="col"> Категория </th> <th scope="col"> № Инвентаря </th> <th scope="col"> Дата эксплуатации </th> <th scope="col"> Наименование инвентаря </th> <th scope="col"> Состояние </th> <th scope="col"> Редактировать </th> </tr> </thead> <tbody> {% if page_obj %} {% for record in page_obj %} <tr> <td> {{record.id}} </td> <td> {{record.depart}} </td> <td>{{record.types}} </td> <td> {{record.category}} </td> <td> {{record.invent_number}} </td> <td> {{record.day}} </td> <td> {{record.name}} </td> <td> {{record.state}} </td> <td> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#recordModal{{ record.id }}">Редакт</button> <!-- Modal --> <div class="modal fade" id="recordModal{{ record.id }}" tabindex="-1" role="dialog" aria-labelledby="recordModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="recordModalLabel">Информация о записи</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p><strong>Департамент:</strong> {{record.depart}}</p> <p><strong>№ кабинета:</strong> {{record.number}}</p> <p><strong>Категория:</strong> {{record.category}}</p> <p><strong>Тип:</strong> {{record.types}}</p> <p><strong>Ответственный:</strong> {{record.otvet}}</p> <p><strong>№ Инвентаря:</strong> {{record.invent_number}}</p> <p><strong>Дата эксплуатации:</strong> {{record.day}}</p> <p><strong>Наименование инвентаря:</strong> {{record.name}}</p> <p><strong>Начальная цена:</strong> {{record.price}}</p> <p><strong>Коментарии:</strong> {{record.info}}</p> <p><strong>Пользователь:</strong> {{record.cr_user}}</p> <p><strong>Дата создания:</strong> {{record.date}}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Закрыть</button> <a href="{% … -
Why the blockquotes section in RichtextuploadingField in django admin is not working?
When I am trying to add blockquotes in my blog details page from Django admin that time I add blockquotes in Django admin and even i saved it but the normal texts are not being the blockquotes in that details page .... and here is my blog-single.html page {% extends "base.html" %} {% load static %} {% static "images" as baseUrl %} {% block title %}Orbitor{% endblock %} <!--header block --> {% block header %} <!-- Slider Start --> <section class="section blog-wrap"> <div class="container"> <div class="row justify-content-center align-items-center"> <div class="single-blog-item text-center"> <img src="{{post.thumbnail.url}}" alt="" class="img-fluid rounded" style="max-width: 500px; max-height: 600px;"> <div class="blog-item-content mt-4"> <h2 class="mt-3 mb-3 text-md">{{post.title}}</h2> <div class="blog-item-meta mb-5"> <span class="text-muted text-capitalize mr-3"><i class="ti-pencil-alt mr-2"></i>{{post.category}}</span> <span class="text-black text-capitalize mr-3"><i class="ti-time mr-1"></i>{{post.pub_date}}</span> </div> </div> </div> </div> <p class="lead mb-4">{{post.head0}}</p> {{ post.head1|safe }} <div class="tag-option mt-5 clearfix"> <ul class="row justify-content-center align-items-center"> <li class="list-inline-item"> Share: </li> </ul> <ul class="tag-option mt-5 clearfix d-flex justify-content-center align-items-center"> <li class="list-inline-item"><a href="#" target="_blank"><i class="fab fa-facebook-f fa-2x" aria-hidden="true"></i></a></li> <li class="list-inline-item"><a href="#" target="_blank"><i class="fab fa-twitter fa-2x" aria-hidden="true"></i></a></li> <li class="list-inline-item"><a href="#" target="_blank"><i class="fab fa-pinterest-p fa-2x" aria-hidden="true"></i></a></li> <li class="list-inline-item"><a href="#" target="_blank"><i class="fab fa-instagram fa-2x" aria-hidden="true"></i></a></li> </ul> </div> <section class="section blog-wrap" > <div class="col-lg-12 mb-5"> <div class="posts-nav bg-gray p-5 d-lg-flex d-md-flex justify-content-between … -
Inbuilt password validator for password reset Django
In the page where the user reset the password (name="password_reset_confirm"), I want to use inbuild django password validator. But unfortunately, I am not able to bring them up on the page. Currently the two password fields are visible and when I change the password, it is working fine but I need to include the password validation that is offered by Django which will check for these below conditions. Your password can’t be too similar to your other personal information. Your password must contain at least 8 characters. Your password can’t be a commonly used password. Your password can’t be entirely numeric. urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.loginPage, name = "user_login"), path('register/', views.registerPage, name="user_register"), path('registration-success/', views.registerSuccessPage, name="register_success"), path('logout/', views.logoutPage, name = "user_logout"), path('', views.home, name = "home"), path('',include('forum.urls')), path('', include('subscription.urls')), path('', include('core.urls')), #password reset path('reset_password/', auth_views.PasswordResetView.as_view(template_name = "password_reset.html"), name="reset_password"), path('reset_password_sent/',auth_views.PasswordResetDoneView.as_view(template_name = "password_reset_sent.html"),name="password_reset_done"), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name = "password_reset_confirm.html"),name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name = "password_reset_done.html"),name="password_reset_complete"), ] -
Bad request with django and javascript ("POST /user_send_info/ HTTP/1.1" 400 98)
Hi guys I basically wanna get some data using Js and put it in a view in django, but I'm getting bad request ("POST /user_send_info/ HTTP/1.1" 400 98) when I try to get it, the request gets activated when we click a button This my Js section <script> var DateTime = luxon.DateTime; const sendBtns = [...document.getElementsByClassName("send_btn")] sendBtns.forEach(btn => btn.addEventListener('click', () => { const companyName = btn.getAttribute("company-name") const userName = btn.getAttribute("user-name") const fullName = btn.getAttribute("full-name") const email = btn.getAttribute("email") const expireDate = btn.getAttribute("expire-date") const version = btn.getAttribute("version") const code = btn.getAttribute("code") function formatDate(inputDate) { const dt = luxon.DateTime.fromISO(inputDate); if (dt.isValid) { const day = dt.toFormat('dd'); const monthName = dt.toFormat('LLL'); const year = dt.toFormat('yyyy'); return day + '-' + monthName + '-' + year; } return inputDate; } const dateFormatted = formatDate(expireDate); const info = { companyName, userName, fullName, email, dateFormatted, version, code, }; console.log(info) fetch('/user_send_info/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}', }, body: JSON.stringify(info), }) .then(response => response.json()) .then(info => { console.log('Response from Django:', info); }) .catch(error => { console.error('Error to send AJAX request:', error); }); })); </script> This my View in Django from django.http import JsonResponse def email_view(request): if request.method == 'POST' and request.is_ajax(): info … -
can not resolve djanngo model issue
I created three apps in my project, and when go to questions models it cannot find a model in Quiz models. please help. Im right in the directory where my manage.py is I tried to change path of my project interpreter, nothing changed -
Web stress testing, the pg encountered an exception, TCP/IP connections on port 5432?
I conducted basic stress testing on the django framework, and my View is as follows class HealthCheckView(APIView): def get(self, request, *args, **kwargs): try: Role.objects.filter().count() except Exception as e: return Response(status=499) return Response(status=status.HTTP_200_OK) I use the following command to start the web service: gunicorn myapp.wsgi:application -c myapp/settings/gunicorn.conf.py gunicorn.conf.py content is as follows: bind = f'0.0.0.0:{GUNICORN_PORT}' worker_class = 'eventlet' workers = 6 Then I used the ab tool for stress testing: ab -n 10000 -c 500 https://10.30.7.7/api/v1/healthz/ When the concurrency is 500, the result is good. When I continued to increase the number of concurrent requests, some of them were unable to connect to the database. django.db.utils.OperationalError: could not connect to server: Cannot assign requested address Is the server running on host "10.30.7.7" and accepting TCP/IP connections on port 5432? The database configuration file is as follows: max_connections = 4096 shared_buffers = 16GB effective_cache_size = 48GB maintenance_work_mem = 2GB checkpoint_completion_target = 0.9 wal_buffers = 16MB default_statistics_target = 100 random_page_cost = 4 effective_io_concurrency = 2 work_mem = 1MB huge_pages = try min_wal_size = 1GB max_wal_size = 4GB max_worker_processes = 20 max_parallel_workers_per_gather = 4 max_parallel_workers = 20 max_parallel_maintenance_workers = 4 How should I conduct the investigation? Reducing the number of concurrent requests can avoid …