Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No wkhtmltopdf executable found in widows
I am not able to solve this error. This error giving in windows. Please tell me how to solve this error. Error: OSError at /1/ No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it or you can pass path to it manually in method call, check README. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf Request Method: GET Request URL: http://localhost:8000/1/ Django Version: 4.0.4 Exception Type: OSError Exception Value: No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it or you can pass path to it manually in method call, check README. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf Exception Location: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\pdfkit\configuration.py, line 38, in __init__ Python Executable: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\Manoj\\Desktop\\sample\\resume_website', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Manoj\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin'] Server time: Mon, 23 May 2022 09:41:24 +0000 -
Django URLs Reverse working but not updating my URL
I'm new to Django 4.0.4. I'm trying to use reverse in model to dynamically change the url without affecting other branch not affecting. url.py: urlpatterns = [ path('', home_view, name='home'), path('products/', product_list, name='product_list'), path('products/<int:myid>/', dynamic_lookup_view, name='product-detail'), path('admin/', admin.site.urls), ] models.py def get_absolute_url(self): return reverse("product-detail", kwargs={"myid": self.id}) html <p> {{instance.id}} <a href="{{instance.get_absolute_url}}">{{instance.title}}</a> </p> Output(working): enter image description here enter image description here Problem: when i change root url for dynamic_lookup_view from 'products/int:myid/' to 'ps/int:myid/' in url.py path('products/', product_list, name='product_list'), path('p/<int:myid>/', dynamic_lookup_view, name='product-detail'), There is no update in my instance.get_absolute_url in my html!? -
Django method to return a dictionary value from request payload
I have a serializer class like this class HousingSerializer(serializers.ModelSerializer[Housing]): class Meta: model = Housing fields = "__all__" depth = 1 with request payload as [{"id":"1234","created_at":"2022-05-20T15:55:43.611922Z","updated_at":"2022-05-20T15:55:43.611938Z","status":"pending"}]% I want to create a method that if giving a Housing 'id', it should return the status from the payload, in this case, it should return the status as 'pending'. -
using google api eith django
I'm trying to connect events withing py project to google calendar. my application doesn't used google login as it is intended for only a small group of people. I've been looking for hours on how to get it done and it doesnt work. Any help is appreciated. models.py class AgendaClient(models.Model): # used to store info(same as enviroment variables) name = models.CharField(max_length=30, null=True, blank=True, unique=True) json = models.TextField(blank=True, null=True) class Event(models.Model): summary = models.CharField(max_length=50, choices=EVENT_CHOICES) description = models.CharField(max_length=50, null=True, blank=True) start_date = models.DateField() google_link = models.CharField(max_length=150, null=True, blank=True) signals.py import datetime import json from django.db.models.signals import post_delete, post_save from google.auth.transport.requests import Request from google.cloud import storage from google.oauth2 import service_account from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from users.models import Lid from .models import AgendaClient, Event, NIEvent # If modifying these scopes, delete the file token.json. try: SCOPES = (AgendaClient.objects.get(name='SCOPES').json).strip("][").split(', ') except: pass def get_service(refresh = False): '''this functions gets and builds the service using the token and the client_secret''' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if len(AgendaClient.objects.filter(name='token'))==1: creds … -
Django - Saving to DB, CSV file without single quotes
I have been trying to save a CSV file with information to add to db. And, is necessary to remove the single quotes, and ")". I already tried doing the replace but, didn't worked. Also, I am doing this by an admin view. I add the csv file with informations to create objects on my db. And, it's from multiple tables. I don't know if I am using the right code or logic for this. def upload_csv(self,request): form = CSVImportForm(request.POST, request.FILES) if request.method == "POST": csv_file = request.FILES['csv_upload'] file_data = csv_file.read().decode("utf-8") csv_data = file_data.split("\n") csv_data = file_data.replace("'", "") try : for x in csv_data: fields = x.split(",") print(fields) create_hospital = {} create_hospital['hospital_name'] = fields[0], create_hospital['hospital_website'] = fields[1], create_hospital['hospital_fiscalAddress'] = fields[2], create_hospital['hospital_shippingAddress'] = fields[3], create_hospital['hospital_region'] = fields[4], create_hospital['country'] = fields[5], create_hospital['hospital_contactPerson'] = fields[6], create_hospital['hospital_contactPhone'] = fields[7], create_hospital['hospital_contactEmail'] = fields[8], create_hospital['hospital_ImageLogo'] = fields[9] created_hospital = HospitalViewRoleForUsers.objects.create(**create_hospital) create_users = {} create_users['FKLab_User'] = fields[0], create_users['user_type'] = "1", create_users['email'] = fields[11], create_users['password'] = BaseUserManager().make_random_password(8), create_users['name'] = fields[10], # create_users['FKLab_User'] = created_hospital.id # create_users['user_type'] = "1" # create_users['email'] = fields[14], # create_users['password'] = BaseUserManager().make_random_password(8), # create_users['name'] = fields[13], # create_users['FKLab_User'] = created_hospital.id # create_users['user_type'] = "1" # create_users['email'] = fields[17], # create_users['password'] = BaseUserManager().make_random_password(8), # create_users['name'] … -
Django admin prefetch content_type model
I used the django debug toolbar to analyse why the calls to my usermodel were so painfully slow within the django admin. There I saw that I had hundreds of duplicate calls to the content_type model: SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 1 LIMIT 21 362 similar queries. Duplicated 4 times. To be honest, I do not understand where these calls come from in the first place but I wanted to pre_fetch the model. However, this seems not to be possible in the normal way because there is actually no ForeignKey or any other kind of direct relationship between the models. How could I reduce those 362 content_type calls? This is the usermodel in question: class User(AbstractBaseUser, PermissionsMixin): """ Base model for the user application """ USERNAME_FIELD = "email" objects = UserManager() username_validator = None username = None email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) title_of_person = models.ForeignKey( TitleOfPerson, on_delete=models.CASCADE, blank=True, null=True ) is_verified = models.BooleanField(default=False) language = models.ForeignKey( Language, blank=True, null=True, on_delete=models.SET_NULL ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self) -> str: return self.email … -
Can i make sfu webrtc in django for live broadcasting of stream to many people ? any source code or tutorial?
I am a python new developer I am planning to do own SFU implementation for broadcasting video conferencing app in addition I am planning to do face recognition with attendance system. So decided to use python. Can you help me by giving answer of above question. can I use django as media server Can I pass the media to the server -
django-import-export want to calculate totals of CSV columns before importing and issuing warning
Using django-import-export, Wanted to import rows into postgresql table only after calculating the total of a particular column of CSV. If it is beyond a limit, want to issue a warning and prevent import else get the page which asks for confirmation of import of this tool. The def before_save_instance method is only for 1 instance at a time. How can I implement for all the rows of the CSV at a time? -
Django migrations no longer running on aws
I am hosting a site via elastic beanstalk and I have a 01_migrate.sh file in .platform/hooks/postdeploy in order to migrate model changes to a postgres database on Amazon RDS: #!/bin/sh source /var/app/venv/staging-LQM1lest/bin/activate python /var/app/current/manage.py migrate --noinput python /var/app/current/manage.py createsu python /var/app/current/manage.py collectstatic --noinput This used to work well bu now when I check the hooks log, although it appears to find the file there is no output to suggest that the migrate command has been ran i.e. previously I would get the following even if no new migrations: 2022/03/29 05:12:56.530728 [INFO] Running command .platform/hooks/postdeploy/01_migrate.sh 2022/03/29 05:13:11.872676 [INFO] Operations to perform: Apply all migrations: account, admin, auth, blog, contenttypes, home, se_balance, sessions, sites, socialaccount, taggit, users, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers Running migrations: No migrations to apply. Found another file with the destination path 'favicon.ico'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Whereas now I just get 2022/05/23 08:47:49.602719 [INFO] Running command .platform/hooks/postdeploy/01_migrate.sh Found another file with the destination path 'favicon.ico'. It will be ignored since only the first encountered file is collected. If this is … -
Django manage.py commands generates error in Cronjob
Whenever I'm running a manage.py command (e.g. migrate, runserver) everything is fine. I'm using the following Cronjob command: * * * * * python3 /home/ec2-user/Project/manage.py migrate However, whenever I'm scheduling a manage.py command in Crontab, the following error comes up: File "/home/ec2-user/project/manage.py", line 22, in <module> main() File "/home/ec2-user/project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ec2-user/.local/lib/python3.7/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/ec2-user/.local/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/ec2-user/.local/lib/python3.7/site-packages/django/db/models/base.py", line 122, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/db/models/base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/db/models/options.py", line 207, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/utils/connection.py", line 15, in __getattr__ return getattr(self._connections[self._alias], item) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/utils/connection.py", … -
Django: URL Path not found jumps into next app
I have two apps: backend shop I my urls in main app dir: path('backend/', include('backend.urls')), path('', include('shop.urls')), the problem is if I write in my url: localhost:8000/backend/abc which not exist Django jumps over to shop.urls and the app is crashing because it can not find the slug and the query goes in fail. How can I prevent if I go to the url /backend/somethingwhichnotexist is returning an 404 and not search in other app urls for this folder? I have thought that this is one of the main reason for split the urls in app folders. Here are some urls from backend/urls.py: from django.urls import path, re_path from . import views as backend_views from django.contrib.auth import views as auth_views from froala_editor import views from django.conf.urls import include urlpatterns = [ path('stamdata/', backend_views.edit_masterdata), path('praefikser/', backend_views.edit_prefixes), path('leverandorer/', backend_views.suppliers_view), path('leverandorer/add', backend_views.add_supplier), ] handler404 = 'backend.views.page_not_found_view' regards Christopher. -
Optional part of url django url
I am trying to set up a url in a Django project so that an API written in JS call can hit it from two different views. For example: localhost:8000/edit/3 will make a call from the / view which corresponds to localhost:8000/ to the function that makes to modifications the resource with id of 3. I would like to use the same API from a different view as follows: localhost:8000/profile/23/edit/3. This basically means that I would like the user to be able to modify the same resource, using the exact same API. Could I possibly set up the path in the urls.py file using re_path instead of path in the urlpattenrs to accomplish this? urlpatterns would look something like this: from django.urls import path, re_path from . import views urlpatterns = [ ... # API routes ... re_path("{profile/<int: user_id>/}edit/<int:post_id>", views.edit), ... ] Please note that the curly braces - {} - are not part of the actual path but enclose the part I would like to be optional. Also, currently path is used instead of re_path. I'm just guessing my goal could be accomplished using regex. Here's part the edit function in views.py: def edit(request, post_id): if request.method == "PUT": … -
Iterate and append the different values from JSON into a variable
I'm trying to iterate and append the QId and Answer from the payload, desired output expected would be like 12|Yes&&13|Yes&&14|Yes&&15|Yes&&16|Yes&&17|Yes&&. All I wanted is to concatenate QId and Answer before it saves to the database. How could I achieve this Qstans = str(qid)+'|'+ answer+'&&'.join([str(qid)+'|'+(answer) for ran in request.data]) this line which append the values output which I'm getting 12|Yes12|Yes&&12|Yes&&12|Yes&&12|Yes&&12|Yes&&12|Yes payload: 0: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 150…} 1: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 151…} 2: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 152…} 3: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 153…} 4: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 154…} 5: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 155…} 6: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 156…} code here: @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': for ran in request.data: qid = ran.get('QId') answer = ran.get('Answer') Qstans = str(qid)+'|'+ answer+'&&'.join([str(qid)+'|'+(answer) for ran in request.data]) print(Qstans) -
Providing custom field in serializer using model data
In Problem model I'm storing a list of users who have done it. In Problem serializer when user will request his data I want to show him if he has done certain problem. So I created custom field in serializer class and want to fill it using models data. this is what I have done. from rest_framework import serializers from dsa.models import Problem class ProblemSerializer(serializers.ModelSerializer): isDoneByUser = serializers.BooleanField(default=False) class Meta: model = Problem fields = ['id', 'topic', 'title', 'link', 'isDoneByUser'] def perform_create(self, serializer): user = self.request.user userlist = serializer.data.get('isDone') print(userlist) if user in userlist: self.isDoneByUser = True But this always setting isDoneByUser = False(default value) please help! -
Django frequently used api
I created a project and 5 applications Now the problem is how many times the particular api is used by all or any particular user Can any one help me We can create new api or anything but I need output for above -
save Jalali(Hijri shamsi) datetime in database in django
I have a Django project, and I want to save created_at datetime in the database. I generate datetime.now with jdatetime (or Khayyam) python package and try to save this in DateTimeField. But sometimes it raises error because the Gregorian(miladi) date of the entry does not exist. what can I do about this? -
Django Access link via multiple name and appnames
I have a application called portfolio_menu that has store.urls and inside store.urls has pruduct.urls that inside has the view with name list page, how do I access it trough the {%url%} tag? I will put below the code: portfolio_menu.urls: app_name = 'portfolio' urlpatterns = [ path('test', include('store.urls', namespace='store')), path('', views.menu), ] store.urls: urlpatterns = [ path('', include('product.urls', namespace='product')), ] product.urls: app_name = 'product' urlpatterns = [ path('', views.ProductListView.as_view(), name='list'), ] the funcion I want to get, but don't know the sintax: <a href="{%url portfolio:store:product:list%}"></a> #I wish something like that -
How to add data-bs-toggle & data-bs-target to my script - Datatables
I want to make a web application on django platform using datatables. I get the data from the database with json and bring it to the screen. I was able to add -edit and -delete buttons as you can see in the photo, but I cannot add functionality to these buttons with javascript. How can I add data-toggle and data-target attributes inside ? In addition, I want to send the id of data in the row with data-target, so that I can edit the data. Thank you for help! enter image description here ..... "ajax": "/json", "columns": [ {"data": "id"}, {"data": "code"}, {"data": "muestra"}, {"data": "ship"}, {"data": "num"}, {"data": "enc"}, {"data": "obv"}, // {"data": "result"}, {"data": "created_at"}, {data: null, render: function ( data, type, row ) { return '<a class="btn btn-outline-success text-center" title="Edit row"><i class="fa-solid fa-pen-to-square" style="color:green !important;"></i></a>'; } }, {data: null, render: function ( data, type, row ) { return '<a class="btn btn-outline-danger text-center" title="Delete row"><i class="fa-solid fa-delete-left" style="color:red !important;"></i></a>'; } }, ], ..... $( "#example" ).on('click','tr a', function() { var tr = $(this).closest('tr'); var data = table.row(tr).data(); console.log(data.id); $($(this).attr('data-bs-toggle','modal')); $($(this).attr('data-bs-target','#editModaldata.id')).model("show"); }); -
I got http instead of https file path in Django
I am working on a project where I users can upload pdf files and sign a signature on it. Although, this implementation works well on local machine which uses http requests, however after I deploy it on a server, the file path's uploaded to the server returns an http path instead of https. Here is models.py from django.db import models from utils.mixins import BaseModelMixin import os from utils import pdf_processor from django.core.files.base import File import requests import time class DocumentFromUrl(BaseModelMixin): pdf_url = models.URLField() rental_bon_number = models.CharField(max_length=255) dossier = models.CharField(max_length=255) company = models.CharField(max_length=255) company_username = models.CharField(max_length=255) user_email = models.EmailField() client_email = models.EmailField() client_username = models.CharField(max_length=255) validity_date = models.CharField(max_length=255) language = models.CharField(max_length=255, null=True, blank=True) message = models.CharField(max_length=255, null=True, blank=True) pdf = models.FileField(null=True, blank=True, upload_to='url_pdf') fields = ['pdf_url', 'rental_bon_number', 'dossier', 'company', 'username', 'user_email', 'client_email', 'client_username', 'language', 'message', "validity_date"] def download_pdf(self): filename = f'media/temp/{time.time()}.pdf' with requests.get(self.pdf_url, stream=True) as r: with open(filename, 'wb') as file: for chunk in r.iter_content(chunk_size=1024): file.write(chunk) return filename def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.pdf: return downloaded_pdf = self.download_pdf() other_part = pdf_processor.pdf_from_dict( {x: y for x, y in self.__dict__.items() if x in self.fields}) merged_files = pdf_processor.merge_pdf_files( [downloaded_pdf, other_part]) self.pdf = File(open(merged_files, 'rb'), name=merged_files.split('/')[-1]) self.save() As you see in the above … -
Platfrom hooks not found when deploying to AWS
I am trying to deploy a django app to elastic beanstalk. This worked well initially but I have recently made a change to the database models and so need to migrate these in the production environment. Looking at old logs I can see there was not a problem with this previously, but now the migrate command is not found: 2022/05/23 07:45:34.726621 [INFO] Executing instruction: RunAppDeployPostDeployHooks 2022/05/23 07:45:34.726634 [INFO] Executing platform hooks in .platform/hooks/postdeploy/ 2022/05/23 07:45:34.726654 [INFO] The dir .platform/hooks/postdeploy/ does not exist I am deploying using eb deploy and I the path mywebsite/.platfrom/hooks/postdeploy/01_migrate.sh exists. Does anyone know why it is not being found? -
How to use django unit tests with elasticsearch?
I use django unit tests to test my application. It worked very well until today. I integrated elasticsearch to the project with the 2 modules django_elasticsearch_dsl and django_elasticsearch_dsl_drf. Since then, almost none of my unit tests are working. I got the same trace for all failed tests: Traceback (most recent call last): File "/home/aurelien/dev/gsport/accounting_bo/tests.py", line 66, in setUp club = create_club() File "/home/aurelien/dev/gsport/dashboard/tests.py", line 38, in create_club club.save() File "/home/aurelien/dev/gsport/clubs/models.py", line 81, in save super().save(*args, **kwargs) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/db/models/base.py", line 739, in save self.save_base(using=using, force_insert=force_insert, File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/db/models/base.py", line 787, in save_base post_save.send( File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/signals.py", line 58, in handle_save registry.update(instance) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/registries.py", line 141, in update doc().update(instance, **kwargs) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/documents.py", line 225, in update return self._bulk( File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/documents.py", line 202, in _bulk return self.bulk(*args, **kwargs) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/documents.py", line 151, in bulk response = bulk(client=self._get_connection(), actions=actions, **kwargs) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 410, in bulk for ok, item in streaming_bulk( File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 329, in streaming_bulk for data, (ok, info) in zip( File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 256, in _process_bulk_chunk for item in gen: File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 195, in _process_bulk_chunk_error raise error File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 240, in _process_bulk_chunk resp … -
How to Handel Create , Update and Delete Image with Django Signals?
I have these Models, I want to change the Name of the Photos in this Pattern (ProductName-ImageId.jpg) I want help in changing the Name of the file, in Update and delete it? is it the Best Practice for doing This? models: class Product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, null=False, blank=False) describtion = models.TextField() price = models.FloatField() inventory = models.PositiveIntegerField() created_time = models.DateTimeField(auto_now_add=True) last_updated_time = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.name def get_absolute_url(self)->str: return reverse("shop:product", kwargs={"pk": self.pk}) @property def photos(self): return ProductImage.objects.filter(product=self) @property def base_photo(self): return self.photos.first().image class ProductImage(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="products/photos") product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self) -> str: return self.product.name signals: from django.db.models.signals import post_delete , post_save from django.dispatch import receiver from .models import ProductImage import os from pathlib import Path from django.conf import settings # This Work On Delete @receiver(post_delete, sender=ProductImage) def my_handler(sender,instance:ProductImage, **kwargs): # Delete the Image after delete the Entry Path(instance.image.path).unlink() @receiver(post_save, sender=ProductImage) def my_handler(sender,instance:ProductImage,created, **kwargs): print() print(instance.image.name) print(instance.image.path) print() if created: old_path =Path( instance.image.path) instance.image.name = f"{instance.product.name}-{instance.id}.jpg" new_path = settings.BASE_DIR / f"media/products/photos/{instance.image.name}" old_path.rename(new_path) instance.save() print(instance.image.path) the two Methods work but when I rename the File the Path Change before Signal : E:\Programming\Python\Django Projects\Django-shop-app\media\products\photos\c-d-x-PDX_a_82obo-unsplash.jpg after Signal : E:\Programming\Python\Django Projects\Django-shop-app\media\Headphones-16.jpg -
Why doesn't Django recognize create_user() when I want to create a User?
I want to create User with User.objects.create_user(username,email,password) where User impored from from django.contrib.auth.models import User but Django doesn't recognize create_user() and When I want to definition of it VsCode says:No Definition found for 'create_user'. I use Django 4.0.4 and python 3.10.4 -
Django validation errors not showing up
So, I was learning Django from a tutorial and came across form validation. The tutor's version had errors pop-up on screen when validation failed but nothing shows up on my form. Here is my forms.py. from django import forms from django.core import validators def check_for_z(value): if value[0].lower() != 'z': raise forms.ValidationError('Name should start with z') class FormName(forms.Form): name = forms.CharField(validators = [check_for_z]) email =forms.EmailField() text = forms.CharField(widget=forms.Textarea) This is my views.py file. from django.shortcuts import render from myformapp import forms def form_name_view(request): form = forms.FormName() if request.method == 'POST': filled_form = forms.FormName(request.POST) if filled_form.is_valid(): # print the form data to terminal print("Validation success") print('Name: ' + filled_form.cleaned_data['name']) print('Email: ' + filled_form.cleaned_data['email']) print('Text: ' + filled_form.cleaned_data['text']) return render(request, 'myformapp/formpage.html', {'form' : form}) And this is my template for the page. <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Form Page</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> </head> <body> <div class="container"> <form method="post"> {{form.as_p}} {% csrf_token %} <input type="submit" class="btn btn-primary" value="Submit"> </form> </div> </body> </html> So whenever i enter a name that's not beginning with z i am supposed to get an exception on the screen but nothing shows up. My … -
Form data is passing in html table
I am submitting the form data by using fetch API and then I want to show some variable values in HTML table. But it's not working as it's supposed to be. I am able to fetch the form data in views.py but I am not able to send it back to the HTML file to show the same data on a table. Without the fetch API submit, everything is working fine as per my need. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where I am going wrong. views.py def home(request): context={} if request.method=="POST": options_value=request.POST['options_value'] value=request.POST['value'] print(options_value,value) context={"options_value":options_value, "value":value} return render(request, 'index.html',context) index.html <form method="POST" action="" id="form"> {% csrf_token %} <select class="form-select" aria-label="Default select example" name="options_value" id="options_value" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> <input type="text" class="form-control" type="text" placeholder="Enter Value" name="value" id="value" /> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" /> </form> <table style="display: table" id="table"> <tbody> <tr> <th scope="row">ProfileUID :</th> <td>{{options_value}}</td> </tr> <tr> <th scope="row">First Nane :</th> <td>{{value}}</td> </tr> </tbody> </table> <script> let form = document.getElementById("form"); let options_value = document.getElementById("options_value"); let val = document.getElementById("value"); const …