Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue Passing Size Parameter from JavaScript to Django Backend
I'm encountering an issue with passing the "size" parameter from my JavaScript function to my Django backend. Here's the relevant code snippet from my Django view: def get_product(request, slug): try: product = Product.objects.get(slug=slug) if request.GET.get('size'): size = request.GET.get('size') print(size) return render(request, "core/product_detail.html") except Exception as e: print(e) And here's the JavaScript function: function get_correct_price(size) { console.log(size); window.location.href = window.location.pathname + `?size=${size}`; } In my HTML template, I'm calling the JavaScript function with the size parameter: <button onclick="get_correct_price('{{ s.name }}')">{{ s.name }}</button> However, when I click the button, the size parameter doesn't seem to be passed to the backend. I've verified that the JavaScript function is being called, and the size parameter is logged correctly in the console. Could you please help me identify why the size parameter is not being received in the backend? Any insights or suggestions would be greatly appreciated. Thank you! -
Items are being added in the cart in multiples of 3 in Django
I am creating a ecommerce website on Django but the problem is that when I add a item in the cart the quantity is set to 3 instead of 1. and when I increase the quantity by clicking one more time. It's quantity becomes 6 instead of 2 and so on. Below is the code from cart.html to add and remove items from the cart. <div class="li-cartstyle cartbodyinformation-quantity"> <p class="quantity-input">{{item.quantity}}</p> <div class="cartquantity-buttons"> <i data-product={{item.product.id}} data-action="add" class="update-cart change-quantity fa-solid fa-angle-up"></i> <i data-product={{item.product.id}} data-action="remove" class="update-cart change-quantity fa-solid fa-angle-down"></i> </div> </div> and below is the code from cart.js var updateBtns = document.getElementsByClassName('update-cart') var user = isAuthenticated ? 'AuthenticatedUser' : 'AnonymousUser'; for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, '\naction: ', action) console.log('USER: ',user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) } else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('Not Logged in') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity': 1} } else { cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Remove Item') delete cart[productId] } } console.log('Cart:', cart) document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/" location.reload() } function updateUserOrder(productId, action){ console.log('User … -
Django Not Sending Tasks to Celery in Production
I am a deployer and delpoys django applications using gunicorn & nginx. Recently, I setup a celery project and here are my services: Gunicorn Project Service [Unit] Description=gunicorn daemon for my project After=network.target [Service] User=user Group=www-data WorkingDirectory=/home/user/myproject ExecStart=/home/user/myproject/myenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/user/myproject/project.sock project.wsgi:application [Install] WantedBy=multi-user.target Celery Service [Unit] Description=Celery Worker Service for my project After=network.target [Service] Type=simple User=user Group=www-data WorkingDirectory=/home/user/myproject ExecStart=/home/user/myproject/myenv/bin/celery -A project worker -l info Restart=always [Install] WantedBy=multi-user.target Celery Logs are stuck at: celery@server ready. But When I run python3 manage.py runserver in production celery logs updates & my task works but not when I use direct service... I tried changing celery to solo worker --pool=solo -l info [celery service] but that didn't work. My Server RAM & CPU is not being fuly utilized so that's not an issue. Thank You! -
Django miss static files after packaging with pyinstaller
I packaged my django project with pyinstaller, my project tree is like below: I did all bellow steps: Copy all static file into static/ with python manage.py collectstatic Add all static file in .spec file like this: datas=[ ('remotescope/templates/remotescope/', 'remotescope/templates/remotescope'), ('static/', 'static'), ('remotescope/logging.conf', '.'),], Update setting.py like this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') But when I try to run my executable file with command of ./RemoteScope runserver 0.0.0.0:8000 --noreload, it info that all static files not found like bellow: 2024-03-30 09:35:51,125 - 139621882558208 - django.request - WARNING - Not Found: /static/admin/css/base.css [30/Mar/2024 09:35:51] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 2288 ... 2024-03-30 09:35:51,134 - 139621795096320 - django.request - WARNING - Not Found: /static/admin/css/login.css [30/Mar/2024 09:35:51] "GET /static/admin/css/login.css HTTP/1.1" 404 2270 BTW: Everything is good in debug mode wiht cmd of "python manage.py runserver 0.0.0.0:8000"(Need modify the setting.py) Anybody has some advice? Thank u very much~ -
SSL/DNS Connection Issue: Too Many Redirections
I have a problem connecting to my VPS server using domain name. I installed SSL certificate on my Debian 10 Docker server and https works only with IP address, when I try to connect with domain name it says 503 Backend Not Found. I tried to do it without nginx and now I configured it with nginx and I am at the moment when it says "Too many redirects". I tried a lot of solutions but I haven't found anything similar to this. Here is my nginx.conf script: events { worker_connections 1024; } http { upstream web { server web:8000; } server { listen 80; listen [::]:80; server_name domain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name domain.com; ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; location / { proxy_pass http://web; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_buffering off; proxy_redirect off; } } } and here is my docker-compose.yml: version: '3' services: web: build: . ports: - "8000:8000" volumes: - .:/app command: python3 manage.py runserver 0.0.0.0:8000 nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - /etc/nginx/nginx.conf:/etc/nginx/nginx.conf - /etc/letsencrypt:/etc/letsencrypt depends_on: - web restart: on-failure How to properly run an SSL server on a domain -
How to send Stripe session checkout parameters in subscription mode
I am quite new to stripe integration, and due to the country I am from, I cannot access the checkout session page due to account activation requirements. So, I am not able to see what all details are visible in the checkout page, and cannot debug it. (I am in test mode) I am quite confused about how I can sent the price id of the product I select. I have created two products in my dashboard, and I am displaying then on the frontend with a pay button that calls the checkout-session endpoint. this is my checkoutSession view class CreateCheckoutSession(APIView): def post(self, request): if request.method == 'POST': try: if request.user.is_authenticated: print(request.user) print(request.user.id) checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.id, payment_method_types=['card'], line_items=[ { 'price': "", 'quantity': 1, }, ], mode='subscription', success_url=os.environ['DOMAIN_URL']+'/dashboard', cancel_url=os.environ['DOMAIN_URL'], ) return Response({'sessionId': checkout_session.id}) else: return Response({'message': 'You need to register first.'}, status=403) except InvalidRequestError as e: error_message = str(e) return Response({'error': error_message}, status=400) else: return Response({'error': 'Method not allowed'}, status=405) I think I should only send the price id or product id (which one am I supposed to send?) of the subscription I want to buy. I am not sure how can I do that. Could anyone please help me … -
Log out view in Django not working. It says method not allow
I tried using Django built in views to create a log out route But it doesn't work. It says method not allow I expected it to log out a user but it doesn't. Always getting error with that. But I imported the login view from Django views and it's working but the log out says method not allowed .Wish someone could help me -
Django parameter stops printing when it reaches the first question mark symbol
I have been learning the weird set-ups of Django! Its very good for web development! I have the following view inside views.py: def callerview(request,paramm): text="this is what was sent : %s"%paramm return HttpResponse(text) the url for this this view at urls.py is as follows: urlpatterns = [ path('callerview/<str:paramm>/', views.callerview, name='callerview'), ] Now, I am sending a word problem to it as the 'paramm'. It works and prints the word problem at localhost. But if the word problem has a question mark it stops printing when it gets to the first ? . so if the url looks like: callerview/why are roses red? why is the sky blue? Then, in the localhost output i will get: why are roses red AND no more! I need to be able to get all the symbols and letters in the word problem! in order to send to OpenAi assistants API. Any advice on how I can keep the ? symbol in the printout of the word problem? thank you -
Difficulty with hosting Multilingual Wagtail site on alwaysdata
my wagtail site has two languages English and German Facing some issues when deploying on alwaysdata.net I'm using these two apps for the multilingual feature in the INSTALLED_APPS list: "wagtail.locales", "wagtail.contrib.simple_translation", This is the middleware: "django.middleware.locale.LocaleMiddleware", these are the settings in settings.py: LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True WAGTAIL_I18N_ENABLED = True USE_L10N = True USE_TZ = True WAGTAIL_CONTENT_LANGUAGES = LANGUAGES = [ ('en', "English"), ('de', "German") ] WAGTAIL_CONTENT_LANGUAGES_FALLBACK = {'default': 'en',} I have the following code in the main urls.py file: urlpatterns += i18n_patterns ( path("", include(wagtail_urls)), prefix_default_language=True, ) The project is running fine locally and also running fine in production server (with DEBUG=TRUE) My problem is, In Production server when I set DEBUG to False the multilingual features gets messed up. I have to manually add /en/ or /de/ at the end of the url to see the pages in the browser for example if I click on the logo (from nav) which has the url set to '/' , it redirects to mydomain.com , but it should be mydomain.com/en/ or mydomain.com/de/ depending on which language currently selected. with DEBUG=True it redirects to mydomain.com/en/ or mydomain.com/de/ when clicking on the logo(you can say homepage) perfectly. What … -
Django deployment with GTK3
I have cretaed a django app, which uses weasyprint to convert html to pdf. This needed GTK3 to be installed on my local system. Now I'm not able to deploy on FL0. I checked the docs which said problems with deployment might be because the code couldn't be run properly. When I first used weasyprint, I was not able to run the app until I installed GTK3 on my laptop. So, I guess this is the issue. Is there any way to do this other than using docker. Or are there any libraries that does not use GTK3. I'll provide any details required. If anyone needs. Thanks. I have an option of containerizing the application. But I'm not able to do so at the moment for some other reasons. That's why I'm asking this -
How to start a download and render a response without hitting disk?
So I have a scientific data Excel file validation form in django that works well. It works iteratively. Users can upload files as they accumulate new data that they add to their study. The DataValidationView inspects the files each time and presents the user with an error report that lists issues in their data that they must fix. We realized recently that a number of errors (but not all) can be fixed automatically, so I've been working on a way to generate a copy of the file with a number of fixes. So we rebranded the "validation" form page as a "build a submission page". Each time they upload a new set of files, the intention is for them to still get the error report, but also automatically receive a downloaded file with a number of fixes in it. I learned just today that there's no way to both render a template and kick off a download at the same time, which makes sense. However, I had been planning to not let the generated file with fixes hit the disk. Is there a way to present the template with the errors and automatically trigger the download without previously saving the … -
why meta class giving error for abstract?
customUser(AbstractBaseUser,PermissionsMixin): id = models.autofield(primary_key = True) class Meta: verbose_name = 'User' verbose_name_plural = 'Users' abstract = True when I wrote abstract = True its giving error like django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'core.CustomUser' that has not been installed but settings.py is properly set. run my project properly -
Adding and Annotated Field in Django Queryset
I have a Django application. I have 3 Django models like this: //Model 1: class ModelAOrders(models.Model): id = models.CharField(primary_key=True, max_length=16) plant_num = models.ForeignKey(Plant, db_column='plant_num', db_index=True, on_delete=models.CASCADE) purchase_order_num = models.CharField(max_length=10) purchase_order_item_num = models.CharField(max_length=5) material_num = models.ForeignKey(Material, db_column='material_num', db_index=True, on_delete=models.CASCADE) current_delivery_dt = models.DateField(null=True) lastest_delivery_dt_modification_dt = models.DateField(null=True) ..... [Other Fields] class Meta: db_table = 'modelA_po' //Model 2: class ModelBFlags(models.Model): purchase_order = models.ForeignKey(ModelAOrders, null=True, on_delete=models.CASCADE) purchase_order_num = models.CharField(max_length=10) purchase_order_item_num = models.CharField(max_length=5) shipped_flg = models.BooleanField(default=False) delivered_flg = models.BooleanField(default=False) expedite_flg = models.BooleanField(default=False) class Meta: db_table = 'modelB_flags' //Model 3: class ModelCBackorders(models.Model): bo_id = models.CharField(max_length=255, blank=True, null=True) bo_start_date = models.DateField(blank=True, null=True) bo_end_date = models.DateField(blank=True, null=True) material_num = models.ForeignKey(Material, db_column='material_num', db_index=True, on_delete=models.CASCADE) mrpcn = models.CharField(max_length=3, blank=True, null=True) mrpcn_mapping = models.ForeignKey(MrpcnMapping, null=True, on_delete=models.CASCADE) planned_delivery_time_value = models.FloatField(null=True) .... [Other Fields] class Meta: db_table = 'modelC_backorders' How can I add an annotated field to my backorder query set based on the SQL code below: SQL Equivalent: SELECT SUM(distinct(opo.outstanding_qty)) FROM apple.modelC_backorders kb LEFT JOIN apple.modelA_po opo ON kb.material_num = opo.material_num LEFT JOIN apple.modelB_flags iof ON opo.id = iof.purchase_order_id WHERE iof.shipped_flg=1 AND opo.outstanding_qty>0 GROUP BY kb.material_num, opo.purchase_order_num, opo.purchase_order_item_num; This is what I have so far but it retuns null for all values. backorders_queryset = ModelCBackorders.objects.annotate( inbound_shipped_qty=Subquery( ModelAOrders.objects.filter( material_num=OuterRef('material_num'), modelbflags__shipped_flg=True, outstanding_qty__gt=0 ).annotate( total_outstanding_qty=Sum('outstanding_qty', distinct=True) … -
Problems with automatic pagination in Django, how to fix duplicate posts?
The problem is that duplicated posts appear during automatic pagination. If the loop {% for post in post_lists %} in the home.html template specifies the output of 5 published posts, then during automatic pagination, duplicates of these 5 published posts are added from the home_list.html template, which is incorrect. Automatic pagination works correctly and displays all published posts properly. The issue only lies with the duplication of the first five published posts; the rest of the posts are not duplicated and are displayed correctly. How to fix this? home.html: {% for post in post_lists %} <div class="post_content" id="post_content"> <!----code for displaying posts goes here----> </div> {% endfor %} <div id="pagination-loader" class="pagination_pages" data-page="1"></div> </div> <script> $(document).ready(function(){ var loadedPage = 1; // Variable to store the loaded page number // Function to load the next batch of posts function loadNextPage() { // Perform an AJAX request to the server var nextPageUrl = '/load-posts/?page=' + loadedPage; console.log("Next page URL:", nextPageUrl); $.ajax({ url: nextPageUrl, type: 'GET', dataType: 'json', success: function(response) { console.log("Response from server:", response); // Check for post data in the JSON response if (response.posts) { // Add HTML with posts to the end of the container $('#post_contenter').append(response.html_posts); // Check if there are … -
django migrate from CIEmailField to collation
I did upgrade from django version to 4.2.8 and then the CIEmailField() is deprecated. I used this CIEmailField on the email field of an user. So I had to change to: email = models.EmailField(unique=True, db_collation="case_insensitive") So the migration is like this: operations = [ CreateCollation( "case_insensitive", provider="icu", locale="und-u-ks-level2", deterministic=True, ), migrations.AlterField( model_name="user", name="email", field=models.EmailField(db_collation="case_insensitive", max_length=254), ), ] But before this changement, with CIEmailField I would .get() an user with this email "test@test.com" or "TEST@test.com". With the case_insensitive collation I made it work only by setting "deterministic=False". But with that, the SQL's LIKE is not working. So every Viewset with "email" in "search_fields" wont work. To make it work, I only found this solution: class UserAdmin(BaseUserAdmin): search_fields = ("email_deterministic", ...) ... def get_queryset(self, request: HttpRequest) -> QuerySet[User]: return ( super() .get_queryset(request) .annotate( email_deterministic=Collate("email", "und-x-icu"), ) ) So I have to do that EVERYWHERE on the App when I have an user to search by his email. But the App is big. Is there any other solution for this? -
Creating Azure B2B login system with Vue.js frontend & Python Django backend
I'm working on a full stack application using Vue.js for the frontend and Python Django for the backend. Now I want to set up my login system based on Microsoft Entra for my tenant (B2B). As my website is a SPA, my initial thought was to set it up with MS docs for public client. See also here. I've got it working. However, as I have a webapp with backend, this approach would be more suitable and safe (right!?). I'm trying to implement this logic, but as this logic is rendering the frontend from the python files I'm confused (as i'm rendering and organizing my front-end logic from the Vue.js side). My question is, what would be the best approach for my application, and how to proceed? I'm aware that my question is broad, but I'm really stuck... Implemented this logic successfully, but this approach is probably more safe/suitable. -
Sending emails in django using smtp
on my site i am trying to reset my password by e-mail using smtp but when i send a password change request i get this error: here is my settings.py : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'expresstest177@gmail.com' EMAIL_HOST_PASSWORD = "ibuc pvmq fkgb acah" EMAIL_USE_TLS = True EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_ADMIN = EMAIL_HOST_USER and urls.py if needed: urlpatterns = [ path('password-reset/', auth_views.PasswordResetView.as_view( template_name='main/password_reset_form.html', email_template_name='main/password_reset_email.html', success_url=reverse_lazy('user:password_reset_done')), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='main/password_reset_done.html'), name='password_reset_done'), path('password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='main/password_reset_confirm.html', success_url=reverse_lazy('user:password_reset_complete')), name='password_reset_confirm'), path('password-reset/complete/', auth_views.PasswordResetCompleteView.as_view(template_name='main/password_reset_complete.html'), name='password_reset_complete'), ] what could be the problem? -
Import CSV file from React front end to Django/Python backend proving unreliable
I am trying to get data from a csv file that is uploaded via a ReactJs front end and then import it into a sqlite database in a Django/Python backend. I am trying to use the same code for several different imports and I have at least two cases that work but when I try to replicate the code, it is not working. It does seem that a csv generated from Excel or from another system does work but I have a mac and if I try to edit the csv either using my VS Code editor or using Numbers (but exporting as a csv) the file then doesn't work. If I inspect the file in VS code though, I can't see any difference between the ones that work and the ones that do not. All are in utf. Is this a problem with the csv? And is there code I can add to diagnose that... and maybe rectify? FRONTEND: import axios from 'axios' import { formatTimeDate } from '../../lib/helpers' class CSVDataLoader extends Component { constructor() { super() this.state = { loading: false, updated: '' } this.handleSubmitData = this.handleSubmitData.bind(this) this.handleFile = this.handleFile.bind(this) } handleFile (e) { e.preventDefault() const fileToUpload = … -
Issue with Django --> Apache WSGI deployment
I have a django app running in VS Code 1.86.2 on a Debian 12 machine using Python 3.11.2. I'm working on a test deployment to Apache 2.4.57 and mod_wsgi 4.9.4. I've been working through docs from Apache and Django. At this point I am able to load html documents from the deployed site, but the Django template tags are not being processed. For example I see the below text in the browser. {% extends "base.html" %} {% block title %}my app{% endblock %} {% block content %} {% csrf_token %} Record Lookup Search Key: {% endblock %} I'm new to the Django and Apache world so hoping for some guidance on where to start diagnosing this issue. Any guidance is much appreciated! -
Should i use GET or POST for request with body in DRF?
I am relatively new to the web development and I am writing backend for webapp for practicing chemical elements and compounds and their formulas in our school. I am using Django and Django Rest Framework. I have encountered a dilemma where I can't decide whether to use GET method or POST method. In frontend it requests compounds and elements from the server with specific criteria. In this view, it recieves request with body (criteria), where are values requested_count, used_ids (to exclude already used compounds/elements), requested_groups, requested_elements (to exclude elements which may students don't know). Then, it filters the database to return the response. I have tested this many times and it is working correctly. My only question is, which method to use in this view. I know that POST should be used when I want to change something in the database and GET to just get query from the database. According to this I should use GET. But I want to send body with that request and that is something what POST typically does. What do you suggest? Thanks Here is the view code: class RequestCompoundsView(views.APIView): serializer_class = RequestCompoundsSerializer def get(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): # Get the … -
My djanco configuration fail to download images but store them in the db without occuring any error
I'm dealing with a problem I have since 2 days, i'm trying to store an image for a car website in a database other than my car one, the creation is successful, it appears in the database but when I try to store the same image in a folder of my application, whatever I try it simply doesn't work, here's my models : class Cars(models.Model): marque = models.CharField(max_length=60) modele = models.CharField(max_length=60) motorisation = models.CharField(max_length=60) couleur = models.CharField(max_length=60) carburant = models.CharField(max_length=60) annee_modele = models.IntegerField() kilometrage = models.IntegerField() nbr_porte = models.IntegerField() nbr_place = models.IntegerField() puiss_fiscale = models.IntegerField() #En chevaux fiscaux puiss_din = models.IntegerField() #En chevaux DIN a_vendre = models.BooleanField(default=True) class CarImage(models.Model): car = models.ForeignKey(Cars, related_name="images", on_delete=models.CASCADE) image = models.ImageField(upload_to='car_images/')models.py Post view : class manage_cars(View): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): c_serializer = car_serializer(data=request.POST) if c_serializer.is_valid(): car_instance = c_serializer.save() images = request.FILES.getlist('image') print(images) for image in images: image_path = handle_uploaded_image(car_instance, image) # Créer l'objet CarImage avec le chemin de l'image CarImage.objects.create(car=car_instance, image=image_path) return JsonResponse({"message": "Voiture et images sauvegardées avec succès"}, status=201) else: return JsonResponse(car_serializer.errors, status=400) serializers.py from rest_framework import serializers from .models import * class car_serializer(serializers.ModelSerializer): class Meta: model = Cars fields = "__all__"serializers.py settings.py : MEDIA_URL = "/media/" MEDIA_ROOT … -
When i implement Cronejob it looks like doesn't take effect
views: @scheduled_task def daily(request): signals.task_daily.send_robust(sender=None) return HttpResponse('ok') signals: from django.dispatch import Signal task_daily = Signal() commad: from django.core import management from django.dispatch import receiver @receiver(task_daily) def clear_old_sessions(*args, **kwargs): management.call_command("clearsessions", verbosity=0) print("Old sessions cleared") when i run and check if is working a have installed in on apps but sessions are not cleand and there is too much dump data -
What oauth 2.0 endpoint is used to validate a bearer token
I have an oauth 2 server implemented using django oauth2 provider. I am implementing the client credentials flow in an api. The client app POSTs to the oauth server's /token/ endpoint to get the access token. That is then sent to my api in the header. What endpoint should the api then call on the oauth server to validate this token, when using a back channel? -
Django view works slow
I have a view in my Django project: @permission_required('storage.add_iteminrelease') @transaction.atomic def add_item_in_release(request, id): release = get_object_or_404(Release, pk=id) if (request.method == 'POST'): add_item_in_release_form = ItemInReleaseForm(request.POST) if add_item_in_release_form.is_valid(): add_item_in_release_form.instance.release = release item = add_item_in_release_form.cleaned_data['item'] if item.count < add_item_in_release_form.cleaned_data['count']: messages.add_message(request, messages.ERROR, 'Кол-во выдачи не должно превышать ' + str(item.count)) return redirect('/releases/details/' + str(id) + '/') item.count -= add_item_in_release_form.cleaned_data['count'] item.save() item_in_release, create = ItemInRelease.objects.get_or_create(item=add_item_in_release_form.cleaned_data['item'], release=release, defaults={'count': add_item_in_release_form.cleaned_data['count']}) if not create: item_in_release.count += add_item_in_release_form.cleaned_data['count'] item_in_release.save() messages.add_message(request, messages.SUCCESS, 'Позиция успешно добавлена') return redirect('/releases/details/' + str(id) + '/') messages.add_message(request, messages.ERROR, add_item_in_release_form.errors.as_data()) return redirect('/releases/details/' + str(id) + '/') else: add_item_in_release_form = ItemInReleaseForm() return render(request, 'add_item_in_release.html', {'add_item_in_release_form': add_item_in_release_form, 'id': id}) and corresponding html template for it with some jQuery code: When I call that view, page is loading up to 10 seconds, but other pages loads instantly. Why that code is so slow? I don't understand. -
MultipleObjects returned when selecting a choice and creating an object for it
In my project I am using react for the frontend and django for the backend. I have the following models, which are related to the issue I am facing class Role(models.Model): ROLE_CHOICES = ( ('Recruiter', 'Recruiter'), ('Manager', 'Manager'), ('Business Development Partner', 'Business Development Partner'), ('Business Development Partner Manager', 'Business Development Partner Manager'), ('Account Manager', 'Account Manager'), ) role = models.CharField(max_length=50, choices=ROLE_CHOICES, null=True, unique=True) def __str__(self): return self.name class UserData(models.Model): fullName = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) aadhaarNumber = models.CharField(max_length=12, blank=True, null=True) dateOfBirth = models.DateField(null=True, blank=True) maritalStatus = models.CharField(max_length=20, blank=True, null=True) emergencyContact = models.CharField(max_length=255, blank=True, null=True) address = models.TextField(blank=True, null=True) phoneNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)], blank=True, null=True) emailID = models.EmailField(validators=[EmailValidator()], blank=True, null=True) emergencyContactNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)], blank=True, null=True) jobTitle = models.CharField(max_length=100, blank=True, null=True) departmentName = models.CharField(max_length=100, blank=True, null=True) joiningDate = models.DateField(blank=True, null=True) employmentType = models.CharField(max_length=100, blank=True, null=True) prevCompany = models.CharField(max_length=255, blank=True, null=True) prevDesignation = models.CharField(max_length=100, blank=True, null=True) relevantSkills = models.TextField(blank=True, null=True) documentAcknowledged = models.BooleanField(default=False, null=True) pfUAN = models.CharField(max_length=100, blank=True, null=True) esiNO = models.CharField(max_length=100, blank=True, null=True) role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.fullName if self.fullName else "Unnamed User" class LoginDetails(models.Model): user_data = models.OneToOneField(UserData, on_delete=models.CASCADE, null = True) username = models.CharField(max_length=255, unique=True, null=True) password = models.CharField(max_length=255, null=True) # …