Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make excel download function in python
The code below is a function to download a table as an Excel file. Table is being merged using DataTable jquery. The problem with the code below is that only two rows are compared and merged. I want to merge the whole data. Please help. The reason that 'register_date_str' is printed twice in values_list is because in the case of values_list, student[0] cannot be used twice. In this case, the value is not output when downloading Excel. What's the best way to use Excel without printing the same value to valuse_list twice? worksheet.write(row, col, str(student[2]) + '-' + str(student[3])) -> Only the 'name' value is printed, not combining two values in one cell. Why? def download_excel: output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() d_format = '%Y-%m-%d' border_center = workbook.add_format({'align': 'center', 'border': 1, 'bold': 1}) bold = workbook.add_format({'bold': True, 'border': 1, 'align': 'center', 'valign': 'vcenter', 'text_wrap': True}) student_header = [["weekday name", 5], ["register_date", 10], ["name - sex", 30], ["phone_number", 15], ["class_name", 15], ["teacher", 15]] row = 0 col = 0 for a_header, width in student_header: worksheet.write(row, col, a_header, border_center) if width is not None: worksheet.set_column(col, col, width) col += 1 students = Student.objects.filter(is_deleted=False).order_by('register_date') \ .annotate(register_date_str=Cast('register_date', CharField())) \ .values_list('register_date_str', 'register_date_str', … -
how you can handle 2 different types of arguments with only one view in django rest framework?
I have urls.py looks like below urlpatterns = [ path("watch-list/<int:pk>/", views.WatchItemDetail.as_view(), name="watch-detail"), path("watch-list/<str:slug>/", views.WatchItemDetail.as_view(), name="watch-detail-slug"), ] so i am sending 2 different type of arguments in same path one is pk and it can also be slug. In my views.py I am writing 2 get request I know this will not work since python not support overloding of methods so how can i achieve like below logic? can we clean up some code also because i am repeating my self with same logic. class WatchItemDetail(APIView): def get(self, request, pk): watch_item = get_object_or_404(WatchItem, pk=pk) watch_item_serializer = WatchItemSerializer(watch_item) return Response(watch_item_serializer.data, status=status.HTTP_200_OK) def get(self, request, slug): watch_item = get_object_or_404(WatchItem, slug=slug) watch_item_serializer = WatchItemSerializer(watch_item) return Response(watch_item_serializer.data, status=status.HTTP_200_OK) This will work only for slug field because previous method is overwritten by next one but i want both of them to work. -
How do I add an API key I already have to Django?
I am working on an REST API assignment, and I have completed it in Django. The last thing I need to do is to implement the authentication, in terms of keys. The project documentation has already given me a key I need to use, I cannot use the key generated by Django. How do I input that key as one of the authorized keys for the Django project? I have already installed the API key framework for Django from this documentation. -
How to sort using string like 'last name' in django queryset
I want to sort Groups with their 'is_favorite' boolean field from model GroupUser. I have two models GroupUser where there is a foreign key to Group model, now when I query Group.objects.filter(is_active=True).order_by('groupuser__group_id__is_favorite') I get groups multiple times. I tried to user distict() on final queryset still no luck. Pls suggest any other way or possible solution. TIA. -
@page :left and @page :left Not working in Django and xhtml2pdf library
Getting Error while applying @page:left{}.. How to solve this error. I searched on google but not get any solution. **page = page + '_' + pseudopage TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'** -
The usage of {% url ...%} vs {{ ... }} in Django templates
I've been practicing Djnago and for that, I was building a blog. While in the process of building it, I was faced with an error, while using the following code: <a href="{% url 'blog_post' post.slug %}"> {{ post.title }} </a> While studying and doing other courses something like this would work fine. But now, it will raise this exception: NoReverseMatch. If I use this code though, it will work just fine: <a href="{{ post.slug }}"> {{ post.title }} </a> While working in different projects the first way would work fine, but this time, it doesn't. My question is why? Here is the code in my urls and on my views. Maybe the mistake is here, not somewhere else. If anyone can explain why this is happening, or where I'm going wrong, it will be greatly appreciated urls: from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.blog_index, name='blog_index'), path('<slug:post_slug>/', views.blog_post, name='blog_post'), ] views: from django.shortcuts import render from .models import Post # Create your views here. def blog_index(request): posts = Post.objects.order_by('- created').filter(published=True) data = { 'posts': posts } return render(request, 'blog/post_list.html', data) def blog_post(request, post_slug): post = Post.objects.get(slug=post_slug) data = { 'post': post } … -
Upload excel in django and display in 4 different webpages
I want to upload an excel file containing 4 columns and display each column in different page. views.py def upload(request): if "GET" == request.method: return render(request, 'myapp/upload.html', {}) else: excel_file = 'WBSdetails.xlsx' pd.read_excel(excel_file, sheet_name = 'ItemDetails') return render(request, 'myapp/structuremaster.html') def structure(request): structures=ConVehicleMaster.objects.all() context={ 'structures':structures } return render(request, 'myapp/structuremaster.html', context) models.py class Excel(models.Model): structure = models.CharField(("Structure"), max_length=150) segment = models.CharField(("Segment"), max_length=150) subsegment = models.CharField(("SubSegment"), max_length=150) element = models.CharField(("Element"), max_length=150) structuremaster.html <tbody> {% for row in WBSdetails %} {% for cell in row %} <tr> <td>{{ cell.structure }}</td> </tr> {% endfor %} {% endfor %} </tbody> I am new to django and have very little idea. Any help will be appreciated. -
Django - method not allowed error after moving ajax request to different app
I have a small form in my django app called home that I submit through jquery ajax request. Below is the setup that I have home urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^submitseries/$', views.submitseries, name='submitseries'), url(r'^getstats/$', views.getstats, name='getstats'), ] home views.py def submitseries(request,id=None): if request.method == "POST": series_url = request.POST.get("series_url") # rest of the processing code that is working fine application urls.py from django.contrib import admin from django.urls import include,path urlpatterns = [ path('', include(('home.urls','home'),namespace="home")), path('series/', include(('series.urls','series'),namespace="series")), path('submitseries/', include(('home.urls','submitseries'),namespace="submitseries")), path('players/', include(('players.urls','players'),namespace="players")), path('admin/', admin.site.urls), ] This setup is working fine but I would like to move this ajax request to a different app in my application that is with name series So I have moved the submitseries function to views.py of series app modified the series urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^$submitseries/', views.submitseries, name='submitseries'), ] ((tried different variations such as series/submitseries/ )) modified the application urls.py as following from django.contrib import admin from django.urls import include,path urlpatterns = [ path('', include(('home.urls','home'),namespace="home")), path('series/', include(('series.urls','series'),namespace="series")), path('submitseries/', include(('series.urls','submitseries'),namespace="submitseries")), path('players/', include(('players.urls','players'),namespace="players")), path('admin/', admin.site.urls), ] rather than pointing it to home.urls I have pointed it to series.url … -
How to send google calendar data to full Calendar in django?
I want to send all google calendar events to full Calendar in django. I have accessed the all events in google calendar of user after they login. Now I have to send these details to full Calendar. def connect_google_api(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json') if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials2.json',SCOPES) creds = flow.run_local_server(port=0) with open('token.json','w') as token: token.write(creds.to_json()) service = build('calendar','v3',credentials=creds) now = datetime.datetime.utcnow().isoformat()+'Z' page_token = None calendar_ids = [] while True: calendar_list = service.calendarList().list(pageToken=page_token).execute() for calendar_list_entry in calendar_list['items']: if "myorganisation" in calendar_list_entry['id']: calendar_ids.append(calendar_list_entry['id']) page_token = calendar_list.get('nextPageToken') if not page_token: break print(calendar_ids) for calendar_id in calendar_ids: count = 0 print(calendar_id) eventsResult = service.events().list( calendarId = calendar_id, timeMin = now, maxResults = 5, singleEvents = True, orderBy = 'startTime').execute() events = eventsResult.get('items',[]) response = JsonResponse(events,safe=False) if not events: print('No upcoming events found') print(events) print("-----------------------------------") I am trying to understand this documentation. It is asking me to provide CalendarId look like abcd1234@group.calendar.google.com. I am printing events in my code and I could not find anything in the format of abcd1234@group.calendar.google.com. print(events) gives some thing like this {kind:calendar#event,'etag': '"381732929101038"', 'id': 'someid', 'status': 'confirmed', 'htmlLink': 'https://www.google.com/calendar/event?eid=', 'created': '', 'updated': '', … -
Reverse for 'new_project' with arguments '('',)' not found. 1 pattern(s) tried: ['new_project/$']
I have just learned to use python and Django for 2 weeks, and I'm trying to build a to-do list. I encountered an error and I might need some advice on it. In the to-do list, there is a page for all projects, and when u click into a project there will be a to-do list. I tried to achieve add a new project function by these codes, but it returns the error as shown in the title, I've been looking into many answers online, most of the reason that caused the issue was because of the inappropriate introduction of URL in HTML file or when u specified more values than form in views.py and u forgot to place them behind url. I still can't understand the error, I would really appreciate it if u could give me some hints on where I might get wrong. Thanks urls.py app_name = 'todo_lists' urlpatterns = [ # homepage path('', views.index, name='index'), # page that shows all projects path('projects/', views.projects, name='projects'), # details of a project path('projects/<int:project_id>/', views.project, name='project'), # add a new project path('new_project/', views.new_project, name='new_project'), views.py def new_project(request): # add new project if request.method != 'POST': # if not submit then … -
Activate venv in vs code
I have been trying to activate a virtual environment using Python's built-in module venv from VS Code without unfortunately any success. I don't get any error message, it simply won't activate. However, If I run the venv\Scripts\activate.bat command from the terminal it don't works ... -
Django-wanted to run the time continuously without refreshing the page
I have developed an Django application where it will take the time based on the timezone and it's working properly but when i refresh the page the time change how could I do without refreshing the page.Even i have no idea to implement it in js or ajax.If anyknow how could be possible to implement django code with the js or ajax. single.html {% extends 'base.html' %} {% block content %} <div class="container-md" id='firstcontainer'> <form action="" method="POST" autocomplete="off"> {% csrf_token %} <div class="container-md"> <h3 id ='user'>Search</h3> <div class="row"> <div class="input-group" > <div class="col-md" > <input class="form-control" type="search" placeholder="Search" id='btnsearch' name="finder" > <br> </div> <div class="pull-left"> <button class="btn btn-outline-success" style="width:70px;height:46px;" type="submit" >Search</button> </div> </div> {% if finder %} {% for list in userb %} <h3>User List</h3> <table class="table table-striped table-hover"> <tr> <!-- <th scope="col">ID</th> --> <td><b> Username </b></td> <td>{{list.username }}</td> </tr> <tr> <td> <b>Email</b></td> <td>{{list.email }}</td> </tr> <!-- <th scope="col"> Format</th> --> <tr> <td><b>Time</b></td> <td id='mydate'> {{mydate}}</td> </tr> <!-- <div class="col"> DateTime</div> --> <!-- <th scope="col">TimeZone</th> --> <!-- <th scope="col">Action</th> --> <!-- <th scope="row">{{list.id}}</th> --> <!-- <td>{{list.username }}</td> --> <!-- <td>{{list.email }}</td> --> <!-- for only the date time --> <!-- <div class="col"> {{my_date}}</div> --> <!-- <div class = 'col'>{{my_date}}</div> --> … -
Unable to update post using models in django
I want to prepare a webpage which outputs book name, publisher and author and want to add the data dynamically using admin panel but unable to do it using below code. Please help models.py from django.db import models class researchpaper(models.Model): title = models.CharField(max_length=200) publication = models.CharField(max_length=200) authors = models.CharField(max_length=200) def __str__(self) -> str: return self.title views.py def publications(request): context = { 'researchposts': researchpaper.objects.all() } return render(request, 'lab/publications.html',context) urls.py path('publications', views.publications, name='publications'), html file {% for paper in object_list %} <tr> <td> <h5>2021</h5> <p style="color: black;"><b>{{paper.title}}1. A minimal model for synaptic integration in simple neurons</b></p> <p style="font-size: 14px;"><i>Physica D: Nonlinear Phenomena, 2021</i></p> <p style="font-size: 14px;"><i>Adrian Alva, Harjinder Singh.</i></p> </td> <td><a href="#" target="blank" style="color: dodgerblue;"><i class="ai ai-google-scholar-square ai-2x" style="padding-right: 10px;"></i></a></td> </tr> <tr> <td> <hr> </td> </tr> {% endfor %} -
Input for field is missing even after i type the correct format on the API
I have coded the following: models.py class Job(models.Model): datetime = models.DateTimeField(default=timezone.now) combinedparameters = models.CharField(max_length = 1000) serializers.py class JobSerializers(serializers.ModelSerializer): class Meta: model = Job fields = ['combinedparameters'] views.py @api_view(['POST']) def create_job(request): job = Job() jobserializer = JobSerializers(job, data = request.data) if jobserializer.is_valid(): jobserializer.save() return Response(jobserializer.data, status=status.HTTP_201_CREATED) return Response(jobserializer.errors, status=status.HTTP_400_BAD_REQUEST) Page looks like this: But if i copy {'device': 177, 'configuration': {'port_range': 'TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/2,TenGigabitEthernet1/0/3,TenGigabitEthernet1/0/4,TenGigabitEthernet1/0/5', 'port_mode': 'Access', 'port_status': 'Disabled', 'port_param1': 'Test\\n1\\n2\\n3', 'port_param2': 'Test\\n1\\n2\\n3'}} And click post, got error saying the single quotes have to be double quotes. So i changed it to : {"device": 177, "configuration": {"port_range": "TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/5", "port_mode": "Access", "port_status": "Disabled", "port_param1": "1\\n2\\n3", "port_param2": "1\\n2\\n3"}} I clicked post again and this time the following error comes out: I dont understand why is it happening. The reason why I key in the long format because this is the format i want to save in my database and this format is created upon saving from my html that creates the job -
Grouping imports together from subdirectories
Say I have a django app where I'm using folders and subfolders to organize my models: app models __init__.py accounts user.py profile.py social facebook.py twitter.py linkedin.py admin.py apps.py urls.py views.py My __init__.py file is as follows: from .accounts.user import User from .accounts.profile import Profile from .social.facebook import Facebook from .social.twitter import Twitter from .social.linkedin import LinkedIn Is there any way to group these imports together or make the code shorter? E.g. (obviously doesn't work) from . import * # or from .accounts import * from .social import * -
Trouble ussing Buddy to test a project using Django REST FRAMEWORK POSTGRE AS DB
Hello I'm currently trying to implement Buddy with my little StartUp that is using DJANGO REST FRAMEWORK as a base. I found a very good example on the site. Unfortunately in the exmaple the used a MySql DB and I'm using Postgre as DB. My settings.py is: # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DBname', 'USER': 'DBuser', 'PASSWORD': 'DBpassword', 'HOST': '', 'PORT': '5432', } } } My Buddy execute look somethig like this: pip install -r requirements.txt cd Project python manage.py test I also created postgre service in Buddy like version: latest, Hostname: postgres, Port:5432, Login:DBuser, Password:DBpassword, Name of a database to be created on container startup: DBname When I run the build Test of my project an error message apears like this: connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Action failed: see logs above for details I really don't now how to fix this, it appears that Buddy creates the database correctly but for some reason django does not reconise that it exists. -
Django Data Migrations: Table Doesn't Exist
I am running into the issue described here: Django: Providing initial group with migrations Specifically, I'm working on legacy code which initialized a 'Countries' table from an init_data file. I now need to add countries (e.g. South Sudan). My understanding is that I should use migrations to add this data, so that the prod database and the test machines will be in sync. Here is my attempted migration: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def forwards_func(apps, schema_editor): Country = apps.get_model('countries', 'Country') db_alias = schema_editor.connection.alias Country.objects.using(db_alias).update_or_create(iso='SS', defaults={'name': 'SOUTH SUDAN', 'printable_name': 'South Sudan', 'iso3': 'SSD', 'numcode': 728}) def reverse_func(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('countries', '__latest__'), ] operations = [ migrations.RunPython(forwards_func, reverse_func) ] The new migrations works on an existing database, but when the test pipeline spins up a fresh machine, it fails with django.db.utils.ProgrammingError: (1146, "Table 'test_cc_dev.country' doesn't exist") I understand from the above link that the problem stems from all of the migrations needing to run as a group. I do not understand the solution. Am I supposed to add the whole table again in this migration? The original data was loaded in the 0001_initial.py file like this: def forwards_func(apps, schema_editor): … -
How to make simple drag&drop in django?
So, I have a django website that do some pandas calculations, it takes excel file and do calculations and returns file. So, I'm trying to make work this drag&drop but it's not working. I get this in my view, will not forward file and not looking right. cal.py def OnlyCAL(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] #pandas calculations response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'cal.html', { 'form': form, 'page_title':page_title }) cal.html {% extends "base.html" %} {% load static %} {% block content %} <style type="text/css"> .box__dragndrop, .box__uploading, .box__success, .box__error { display: none; } .box.is-dragover { background-color: grey; } </style> <form class="box" method="post" action="{% url "rec" %}" enctype="multipart/form-data"> {% csrf_token %} <div class="box__input"> <input class="box__file" type="file" name="files[]" id="file" data-multiple-caption="{count} files selected" multiple /> <label for="file"><strong>Choose a file</strong><span class="box__dragndrop"> or drag it here</span>.</label> <button class="box__button" type="submit">Upload</button> </div> <div class="box__uploading">Uploading…</div> <div class="box__success">Done!</div> <div class="box__error">Error! <span></span>.</div> </form> <script> if (isAdvancedUpload) { var droppedFiles = false; $form.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) { e.preventDefault(); e.stopPropagation(); }) .on('dragover dragenter', function() { $form.addClass('is-dragover'); }) .on('dragleave dragend drop', function() { $form.removeClass('is-dragover'); }) .on('drop', … -
how to change page data without refresh using django
I am working on a project like live currency prices and I need to change page data without refresh page.In this project I am using Django and Sql server. I did not get results using the triggers and Ajax because ajax needs an event to run like clicking or timer(that very bad for performance) and triggers can not be processed by Django. Is there a way to do it? Thank you for your help -
Translate sql query on Django
I have two tables: students (that has all the students of a school) and suspensions (all the students that are suspended) id name school_grade 1 Jeff 1 2 Dave 1 3 Susan 2 4 Will 2 5 Peter 3 id reason student_id 1 Missed class 1 2 Arrived 20 times late 2 3 Fight 5 So I need to get statistics of which students of different grades are suspended. So, my query is this. SELECT school_grade, count(school_grade) from students JOIN suspensions ON students.id=suspensions.student_id GROUP BY school_grade; And this query gives me exactly what I want. school_grade number of suspension 3 1 1 2 But I don't understand how to make this query on django. -
I how to check for authenticated user and show then show a different content in django
What am trying to do is have two different user locations. One is from my user model and the other is default from view. I want that anytime a user is authenticated, the location from the model shows but if not logged in the default location should be passed to the view. Views.py class Home(generic.TemplateView): template_name = "Home.html" def get_context_data(self, **kwargs): context = super(Home, self).get_context_data(**kwargs) if User.is_authenticated: map_location = self.request.user.location_on_the_map else: map_location = Point(longitude, latitude, srid=4326) context.update({ 'job_listing': JobListing.objects.annotate( distance=Distance("location_on_the_map", map_location) ).order_by("distance")[0:6] }) return context -
Django 403 Forbidden POST/PUT when requesting from Reactjs (strict-origin-when-cross-origin)
I have a reactjs project that makes requests using API to django-rest-framework. It was working fine and this problem suddenly appeared which is super weird. I'm already using django-cors-headers. My settings.py: INSTALLED_APPS = [ ... 'rest_framework', "corsheaders", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True My reactjs request: fetch('/api/user/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(obj) }) I just want to emphasize that it was working fine and suddenly after editing the code, it stopped working. -
how to prevent user from submitting the same form twice
I have the codes below in my views and models. But I want a situation in which a user cannot submit the same form twice. once a user submits the form he or she can only see a preview of what has been submitted but is unable to submit the same form. Any help would be highly appreciated. Thanks #views.py def index(request): form = MembershipForm() if request.method == 'POST': form = MembershipForm(request.POST) if form.is_valid(): form.save() return redirect("home") return render(request, 'index.html', {'form': form) #models.py class Membership(models.Model): fullname = models.CharField(max_length=500, blank=True, null=True) location = models.IntegerField(default='0',blank=True, null=True) department = models.IntegerField(default='0',blank=True, null=True) last_update = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return str(self.fullname) -
Dynamically change Char/IntegerField choices for each Model instance
I'm wondering if it's possible to dynamically change the choices of an IntengerField for each instance of a Model. I'm working with a video game API and i want PLATFORM_CHOICES to be unique for each game, since not every game is released on the same platform. For example, on the first iteration, the platform choices for game1 could be PlayStation & Xbox, but game2 could be PlayStation, Xbox, Nintendo, & PC. models.py class TestModel(models.Model): PLATFORM_CHOICES = [] platform_type = models.IntegerField(choices=PLATFORM_CHOICES, null=True) game = models.CharField(max_length=200, null=True) api.py def get_games(self): new_url = "{}{}".format(self.url, 'games') data = requests.get(new_url, params=self.query).json() games = data['results'] for game in games: t = TestModel() for platform in game['platforms']: id = platform['platform']['id'] # int name = platform['platform']['name'] # str t.PLATFORM_CHOICES.append((id, name)) # add tuple to list t.save() t.game = game['name'] t.save() I've tried different variations of this but the IntField always ends up empty. Please let me know if there's anymore info I can provide. -
Django Rest Framework - Unable to UPDATE Table Via AJAX through PUT HTTP Method
I have a small project where I have built an API and it feeds the frontend via ajax. All the other CRUD functions work apart from UPDATE. When I use Postman, the UPDATE API works perfectly. So I'm guessing the problem is on the ajax side. I have searched for a solution to no avail. Some help on this would be highly appreciated. Here is my UPDATE API @api_view(['PUT']) def EditProductAPI(request, id): product = Products.objects.get(id=id) serializer = ProductSerializer(instance=product, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_304_NOT_MODIFIED) My Update From <!-- Edit Product Modal --> <div class="container"> <div class="modal fade" id="editProduct" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit Product</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="editProduct" action=""> {% csrf_token %} <input type="hidden" id="Myid" value=""> <div class="form-group mb-3"> <label for="p-name">Product Name</label> <input type="text" class="form-control" id="p-name" name="name" placeholder="Product Name" required> </div> <div class="form-group mb-3"> <label for="p-category">Category</label> <select class="form-control form-select" aria-placeholder="Category" id="p-category" name="category" required> <option selected disabled>Category</option> <option value="Electronics">Electronics</option> <option value="Furniture">Furniture</option> <option value="Toys">Toys</option> <option value="Hardware">Hardware</option> <option value="Medicine">Medicine</option> <option value="Groceries">Groceries</option> </select> </div> <div class="form-group mb-3"> <label for="p-quantity">Quantity</label> <input type="number" class="form-control" id="p-quantity" name="quantity" placeholder="Quantity" required> </div> <div class="form-group mb-3"> <label for="p-price">Price</label> <input type="number" …