Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Saving database with manipulated .csv file | Error: “” value has an invalid date format
I have csv file and It is updating by another platform periodically. I am trying to import this csv file to my database. But csv file style (like date field, blank fields or choice fields) are not matching with django. So I need to manipulate this file and then I am going to import to my database. Even I edit this csv file in my script and looks good as a csv file, still I got following errors. Error django.core.exceptions.ValidationError: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] Aslo I have another error ValueError: Field 'socialNumber' expected a number but got ''. My Models class Personnel(models.Model): personnnelNumber = models.IntegerField(primary_key=True) name = models.CharField(max_length=50, null=True, blank=True) dateEmployment = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) dateTermination = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) cardCode = models.IntegerField(null=True, blank=True) SapCode = models.IntegerField(null=True, blank=True) country = models.CharField(max_length=50, null=True, blank=True) idNo = models.IntegerField(null=True, blank=True) gender = models.CharField(max_length=50, null=True, blank=True) birthdate = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) socialNumber = models.IntegerField(null=True, blank=True) dateEmploymentRD = models.DateField( auto_now=False, auto_now_add=False, null=True, blank=True) dateTerminationRD = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) task = models.CharField( max_length=50, null=True, blank=True) workTime = models.IntegerField(choices=((1,'Full Time'),(2,'Part Time')), null=True, blank=True) graduateLevel = models.CharField( max_length=50, null=True, blank=True) highSchoolname = models.CharField( max_length=50, null=True, … -
Django Maximum Recursion Depth Exceeded. View loops infinitely
I am writing an application that will decode make, model, and year information for provided VIN numbers from cars. The script works standalone but when integrated into my django app and called through a button click on my web app, the view begins to loop infinitely and raises a RecursionError. I will provide relevant code below base html template <!DOCTYPE html> {%load static%} <Html> <title>What the F*cking F*ck</title> <head> </head> <h1>Here I will attempt to recreate the Working Title File in a somewhat nice looking format. </h1> <h4>We'll see what happens</h4> <div> {% block header %} <p>Upload an IPDF with the Browse Button below</p> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% endblock %} <p><a href="{% url 'wtf' %}">Return to upload</a></p> <p> </div> <div id="address"> {% block address %} <p>This is where stuff would render if you had uploaded something. But you didn't. Or it broke. So shame on both of us.</p> {% endblock %} </div> </Html> address_render.html (inherits from base, also called wtf). This one works as intended. When I click the button here to call the view vin_decode it breaks. {% extends "wtf2/wtf.html" %} <script scr='../../jquery-3.6.0.js'> </script> {% block header %} <p>Successful Address … -
Question: 'tuple' object has no attribute 'get' [closed]
def search_jobs(request): if request.method == "POST": searched = request.POST['searched'] jobs = Job.objects.filter(job_title__contains=searched) return render(request, 'jobs/jobs_searched.html', {'searched':searched, 'jobs':jobs}), else: return render(request, 'jobs/jobs_searched.html') Traceback Switch to copy-and-paste view C:\Users\Jams\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\Jams\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\deprecation.py, line 119, in call response = self.process_response(request, response) … ▶ Local vars C:\Users\Jams\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\middleware\clickjacking.py, line 26, in process_response if response.get('X-Frame-Options') is not None: … ▼ Local vars -
How to clear Django-imagekit cache?
on my ubuntu VPS, I process thousands of images through django-imagekit. My code class Thumbnail(ImageSpec): processors = [ResizeToFit(1200)] format = 'WEBP' options = {'quality': 90} Main_image = open('path/to/image.jpg','rb') Preview_gen = Thumbnail(source=Main_image) Preview = Preview_gen.generate() but after few hundred processes it stops at: Preview = Preview_gen.generate() but after restarting the server it works fine for the next few hundreds maybe it's related to caching so, how to clear the cache or any other solution -
Issue joining data in graphene-django with a ManyToMany field
I've been trying to find a good example for returning a query set with joined data across a ManyToMany field, but I've not found one. Given the following model: class Task(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) detail = models.ManyToManyField("Detail", through="TaskDetails") class Detail(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) detail_name = models.CharField(max_length=250) class TaskDetails(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) task = models.ForeignKey("Task", related_name="detail_tasks") detail = models.ForeignKey("Detail", related_name="task_details") detail_value = models.CharField(max_length=250) I'd like to return the data for Task with it's related details. Based on the answer on this question, I tweaked my schema to the following: class TaskDetailsType(DjangoObjectType): class Meta: model = TaskDetails fields = ("id", "detail_name", "detail_value") detail_name = graphene.String() def resolve_detail_name(value_obj, info): return value_obj.detail.detail_name class TaskType(DjangoObjectType): class Meta: model = Task fields = ("id", "task_details") task_details = graphene.List(TaskDetailsType) def resolve_task_details(value_obj, info): return value_obj.detail_tasks When I run this though, I get an error: {'errors': [{'message': 'User Error: expected iterable, but did not find one for field TaskType.taskDetails.'}, {'message': 'User Error: expected iterable, but did not find one for field TaskType.taskDetails.'}, {'message': 'User Error: expected iterable, but did not find one for field TaskType.taskDetails.'}], 'data': {'getInboxTasks': [{'id': 'a430e49d-c9c3-4839-8f2c-aaebbfe9ef3a', 'taskDetails': None}, {'id': '74c8dacc-1bfd-437a-ae34-7e111075ac5e', 'taskDetails': None}, {'id': '10956caa-d74f-4a01-a5cf-9cac6a15c5a3', 'taskDetails': None}]}} -
Complex query, getting the sum of a group of brands django
So here is the following issue, i am basically trying to bring up a query that display a top 10 brands table. And i am currently stuck at trying to 'join up' the brands. As you can clearly see, i am uncapable of putting the brands at the same group and count the number of sales, of that specific brand group. I tried the following query, but it didnt work out query2= DataDB.objects.annotate(marcas=Count('marca')).order_by('marcas')[:10] And here is my tables code <table class="table table-striped table-dark" width="100%"> <thead> <th>Marca</th> <th>N* de vendas</th> </thead> {%for q in query2 %} <tr> <td>{{q.marca}}</td> <td>{{q.marcas}}</td> </tr> {% endfor%} </table> Would really appreciate a little help here, dont actually know if the issue is on display or query. -
How to use temporary files in AWS - moving from BytesIO
I have a Django app hosted on Heroku, with the static files in an AWS bucket. On my localhost I had been using xhtml2pdf to render some pdfs. I have been using the code below. Does anyone know how I could achieve something similar with AWS bucket (possibly using Boto3)? def render_to_pdf(template_src, context_dict={}): template=get_template(template_src) html=template.render(context_dict) result = BytesIO() pdf=pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None -
'tuple' object has no attribute 'filter'
I'm trying to return two tables in two querysets, using objects attributes filter and get. I tested on print function these two querysets and they are returning right. But the error continues. I believe that mistakes happen only in views.py. def cliente_detail_view(request, slug): template_name = 'reconhecimento_facial/cliente_detail.html' obj = Cliente.objects.filter(Q(slug__icontains=slug) | Q(slug__iexact=slug)) cliente = Cliente.objects.get(slug__icontains=slug).id_cliente print(cliente) queryset2 = Exame.objects.filter(cliente_fk=cliente) print('cliente_detail_view') print(obj) context = { "object": obj, "object2": queryset2 } return render(request, template_name, context) class ClienteDetailView(DetailView): def get_queryset(self): slug = self.kwargs.get("slug") print('--------') print(slug) print('--------') if slug: queryset = Cliente.objects.filter(slug__icontains=slug) cliente = Cliente.objects.get(slug__icontains=slug).id_cliente print(cliente) queryset2 = Exame.objects.filter(cliente_fk=cliente) #queryset3 = Dependencia.objects.get(id_cliente1=cliente) #queryset4 = Dependencia.objects.get(id_cliente2=cliente) else: queryset = Cliente.objects.all() queryset2 = Exame.objects.all() print('ClienteListView') print(queryset) print(queryset2) return queryset, queryset2 -
Django object search
I am trying to make a search bar for some QuerySet objects. How can I make this code cleaner? filtered = test.filter( Q(user__icontains=query) | Q(notes__icontains=query) | Q(fees__icontains=query) | Q(date__icontains=query) ) This code looks through all the fields of the model for the search query. I am thinking a way to make this cleaner is somehow pass in a list like ['user', 'notes', 'fees', 'date'] and then running __icontains for all the items in the list. -
How to use a nested serializer dynamically for two serializers?
I am working on an API, with Django, Django Rest Framework, and trying to achieve these(ad described) First Serializer class DeviceConfigSerializer(serializers.ModelSerializer): config = serializers.JSONField(initial={}) context = serializers.JSONField(initial={}) templates = FilterTemplatesByOrganization(many=True) class Meta: model = Config fields = ['backend', 'status', 'templates', 'context', 'config'] extra_kwargs = {'status': {'read_only': True}} Now I have two nested serializer containing the above serializer for the LIST and DETAIL endpoints:- Second Serializer class DeviceListSerializer(FilterSerializerByOrgManaged, serializers.ModelSerializer): config = DeviceConfigSerializer(write_only=True, required=False) class Meta(BaseMeta): model = Device fields = ['id','name','organization','mac_address','key','last_ip','management_ip', 'model', 'os', 'system', 'notes', 'config', 'created', 'modified',] Third Serializer class DeviceDetailSerializer(BaseSerializer): config = DeviceConfigSerializer(allow_null=True) class Meta(BaseMeta): model = Device fields = ['id','name','organization','mac_address','key','last_ip','management_ip', 'model','os','system','notes','config','created','modified',] Now, I am using the same serializer for List, and Detail endpoint, but for the list endpoint I have set the nested serializer as write_only=True, But What I am trying to do with the list endpoint that is DeviceListSerializer serilaizer is that out of all the fields from the DeviceConfigSerializer, I want the status, and backend fields to be readonly and others fields as write_only. Presently with this configuration I am getting the response from the DeviceListSerializer as this:- { "id": "12", "name": "tests", "organization": "-------", "mac_address": "-------", "key": "------", "last_ip": null, "management_ip": null, "model": "", "os": … -
Is there is compulsory to stop a thread in python?
I have started a thread for sending email, Does my code need to stop a thread. I started a thread from view.py file Please inform me if I need to change my code view.py ForgotPassword(user, full_name).start() task.py import threading from django.contrib.auth.tokens import default_token_generator from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from Settings.models import Global class ForgotPassword(threading.Thread): def __init__(self, user, full_name): self.user = user self.full_name = full_name threading.Thread.__init__(self) def run(self): site = Global.objects.get(pk=1) subject = "Password Reset Requested" c = { "email": self.user.email, 'domain': '127.0.0.1:8000', 'site_name': site.visible, 'site_full_name': site.hospital, 'site_email': site.email, 'user_name': self.full_name, 'site_address': site.address, 'uid': urlsafe_base64_encode(force_bytes(self.user.pk)), 'user': self.user, 'token': default_token_generator.make_token(self.user), 'protocol': 'http', 'facebook': site.facebook, 'contact': site.contact, } html_template = render_to_string('Email_templates/password_email_template.html', c) from_email = site.hospital + " " + "<" + site.email + ">" try: send_mail(subject, None, from_email, [self.user.email], html_message=html_template) except BadHeaderError: return HttpResponse("Invalid Header") -
Update Bootstrap modal body with pk/id for Django form
I have table with data provided by Django. Each row has naturally different data and different 'pk'. I'd like to use Bootstrap Modals to render form and send it back to Django, to edit the fields. I spent hours to find and try different solutions from SO, but it still don't work for my case. Please help as I'm out of options now. Here is pure code I manage to produce: HTML: <a data-bs-toggle="modal" data-bs-target="#updatemodal" title="Update" class="btn btn-icon btn-light btn-hover-primary btn-sm mx-3" data-url="{% url 'event:event-update' event.pk %}">link </a> <div class="modal fade" tabindex="-1" id="updatemodal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Update Event</h5> <!--begin::Close--> <div class="btn btn-icon btn-sm btn-active-light-primary ms-2" data-bs-dismiss="modal" aria-label="Close"> <span class="svg-icon svg-icon-2x"></span> </div> <!--end::Close--> </div> <div class="modal-body"> <form id="update-form" method="POST" action="#"> <button type="submit" class="btn btn btn-danger font-weight-bold ml-2"> Update Event </button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close </button> </div> </div> </div> </div> Javascript: <script> $('#updatemodal').on('show.bs.modal', function (e) { var trigger = $(e.relatedTarget).data('url'); console.log(trigger); document.getElementById("update-form").setAttribute("action", trigger); }); </script> Note: I use BS 5.0.0-beta3 + JQ 3.6 As for now I get it from here: <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> -
type object 'ContactCenter' has no attribute 'objects'
I'm getting a weird error for the first time, can some one help please from .models import ContactCenter from django_tenants.utils import schema_context from apps.contacts.models import Contact # Create your views here. class ContactCenter: def test(self, logged_user_id = None): obj = [] contacts = ContactCenter.objects.filter(name = "john") error : type object 'ContactCenter' has no attribute 'objects' -
What is a CBV mixin in Django?
I was reading about the Django UserPassesTestMixinmixin, and I came across the term CBV Mixin. What is this, and how is it useful? Is a CBV Mixin a general type of mixins, and are there CBV mixins in any other framework apart from Django? -
How to increase SSL timeout on Amazon EC2 instance?
The ADFS server I have to leverage is hosted on Azure in a different country. Occasionally I get an error HTTPSConnectionPool(host='<sts server name>', port=443): Max retries exceeded with url: /adfs/oauth2/token/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)'))) Just need to increase the SSL timeout between my Amazon EC2 instance hosted Django site, and the Azure hosted ADFS server. How would I do that? -
My images are not being visualized Django
Hi i´m doing an ecommerce project with Django and i have the following issue; when i upload a product from my admin panel the product image is not shown just the place holder as if there was an image in there. proyecto/proyecto/settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') tienda/urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) tienda.html: {% extends 'tienda/index.html'%} {%load static%} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img src="{{product.image.url}}" alt="" class="thumbnail" > <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Agregar al carrito</button> <a class="btn btn-outline-success" href="">Ver</a> <h4 style="display: inline-block; float: right;"><strong>${{product.price|floatformat:2}}</strong></h4> </div> </div> {%endfor%} </div> {% endblock %} The first time i did this worked and suddenly i refreshed one time the page and never again where the images shown in my page. -
how to display plotly json object in html template
I have a django application that displays a few charts generated using plotly. This is my views.py file def assam(request): const_list = pd.read_csv('./const.csv').Const.unique() part_list = pd.read_csv('./part_list.csv').abbr.unique() part_bargraph = main_graph(part_list, len(const_list)) context = {'main_graph': part_bargraph} return render(request, 'home.html', context) The main_graph is a function that takes a list and an int value as parameters and generates a plotly graph. This graph is then returned as a json object using the plotly.io.to_json method. I want to display this graph in an HTML template. This is what I am doing right now <div class="main_graph"> {% if main_graph %} <script> { { main_graph: "safe" } } </script> {% else %} <p>No graph was provided.</p> {% endif %} </div> But this does not seem to work. What am I doing wrong? Thanks in advance -
calling a template and return it as a string in django from view
In my django project I want to call my template with from views.py with a list view and return it like a string in my view function. This is because I want to print the string as an pdf. Is it possible to call the template with context_object_name so it can generate the html page and then return it an an string to my pdf generator, weasyprint? views.py: def eprint(request): g=request.GET checked=g.getlist('marked[]') print(checked) res=[Concert.objects.get(pk=l) for l in checked] con='<table class="table table-hover table w-auto text-xsmall cellspacing="1" cellpadding="1" table-striped table-sm">' paragraphs=['first paragraph', 'second paragraph', 'third paragraph'] # html_string=render_to_string('test', {'paragraphs': paragraphs}) hres=render(request,'events.html',{'cc':res}) html=HTML(string=hres) # html=HTML(string=html_string) html.write_pdf(target='pdf/test.pdf'); fs = FileSystemStorage('pdf') with fs.open('test.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="test.pdf"' return response return response class Events(ListView): context_objecjt_name='cc' model=Concert template_name='kammem/events.html' events.html: {% for l in object_list %} <tr> <td> <form> <label><input type="checkbox" id={{l.pk}} name="checkb"></label> <form> </td> <td><a href="eupdate/{{l.pk}}"><i class="bi bi-pencil-square"></i></a></td> <td><a href="edelete/{{l.pk}}"><i class="bi bi-trash"></i></a></td> <td>{{l.pk}}</td> <td>{{l.cname}}</td> <td><a href="detail/{{l.venue.pk}}">{{l.venue}}</a></td> <td>{{l.date}}</td> <td><a href="detail/{{l.organizer.pk}}">{{l.organizer}}</a></td> <!-- <td><a href="detail/{{l.vadress.pk}}">{{l.vname}}</a></td> --> <!-- <td>{{l.organizer}}</td> --> <td>{{l.antmus}}</td> <td>{{l.män1}}/{{l.kvinnor1}}</td> <td>{{l.publik}}</td> <td>{{l.män2}}/{{l.kvinnor2}}</td> </tr> {% endfor %} </tbody> -
how can I extends from another class
I'm new in Python/Django and I'm working on a little project to improve my self, I would like to know how can I extends or how can I call a function from another class I already tried but I got some errors this is my code : first class # Create your views here. class ContactCenter(object): def myFunction(self, logged_user_id = None): print("hello") second class from apps.contact.views import ContactCenter class ListModelMixin(object): def list(self, request, *args, **kwargs): ContactCenter.myFunction() -
No Data is Getting Sent to Django Rest Framework API
I am trying to send the Post objects to my API for posts where followers of a user each have a Source_id and Source_id=Post.sourceID. Basically, I am trying to return all the Post objects for the followers of a user in order to then render a feed. But, I am running into a problem because my API is not returning any data, even though I made sure the data is in the database. In my views.py, this is what I am doing: class FeedAPI(ObjectMultipleModelAPIView): #lookup_url_kwarg = 'id' def get_querylist(self, *args, **kwargs): id = self.kwargs['id'] if id != None: profile = Profile.objects.filter(id=id) if len(profile) > 0: data = ProfileSerializer(profile[0]).data return Response(data, status=status.HTTP_200_OK) querylist = [ {'queryset': Profile.objects.all(), 'serializer_class': ProfileSerializer}, {'queryset': Post.objects.all(), 'serializer_class': PostSerializer}, {'queryset': Source.objects.all(), 'serializer_class': SourceSerializer}, ] props = Source.objects.filter(profile_id=id) followers = [f.pk for f in Profile.objects.filter(followers__in=props)] return followers feedPosts= [] postID = Post.objects.filter() i=0 length = len(followers) #while i < length: #feedPosts = list(Post.objects.filter(Source_id=Post.sourceID)) #return feedPosts(i) #i+=1 for x in followers: feedPosts = Post.objects.filter(Source_id=followers) return feedPosts(x) return Response(feedPosts, status=status.HTTP_200_OK) The url is path('feed/<int:id>', views.FeedAPI.as_view()), models class Profile(models.Model): user = AutoOneToOneField(User, default=True, on_delete=models.CASCADE) sourceID = models.ForeignKey('Source', on_delete=models.CASCADE, related_name='+', blank=True, null=True) followers = models.ManyToManyField( 'Source', related_name='+', default='', blank=True, null=True) following = … -
Run django and postgresql on two computers
We are developping a website with two developpers. The first one is a superuser but not the second one. We don't have a server but only a mutualized server. The issue is that when we need to do python manage.py migrate (or makemigrations), we have to log in the website of the server provider and to open the security consol (which is only open for ten minutes), which takes 2/3 minutes each time. When i was working alone, it was faster to have a local database on my computer and to do a quick manage.py migrate in conda. Is it possible to use my personnal conda window to do a manage.py makemigrations on a distant mutualized database ? If not what would be the best solution to share the database ? Thanks a lot -
how to use pagination
def subcategoryProduct(request, subcategory_slug=None): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] subcategory = None subcategories = SubCategory.objects.all() categories = Category.objects.all() product = Product.objects.filter(available=True).order_by('?') page = request.GET.get('page',1) paginator = Paginator(product,2) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) if subcategory_slug: subcategory = get_object_or_404(SubCategory, slug=subcategory_slug) products = paginator.object_list.filter(subcategory=subcategory) -
Django No module named win32com?
I got this issue. I have to deploy my Django project from a Mac computer(OSX). But I get this error: No module named win32com Is there a way or alternative library? This is where I need it: views.py excel = win32.gencache.EnsureDispatch('Excel.Application') excel.Visible = True ex = excel.Workbooks.Open(save_path) ex_sheet = ex.Worksheets('Finansal Tablolar_formul') ex_sheet.Columns.AutoFit() ex_sheet_2 = ex.Worksheets('Finansal Tablolar_formul') ex_sheet_2.Columns.AutoFit() ex.Save() ex.Close(True) excel.Application.Quit() -
Django extends tag loading wrong templates
I'm building a new site in Django using TailWind CSS and have been trying to utilize to the use of extends tags and block content. This is the base.html file: {% load static %} <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]> <html class="no-js"> <!--<![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>{% block title %}{% endblock %}</title> <meta name="description" content="{% block description %}{% endblock %}"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="canonical" href=""/> <link rel="stylesheet" type='text/css' href="{% static 'css/style.css'%}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,500;0,600;1,400;1,800&display=swap" rel="stylesheet"> </head> <body> <!-- START NAV --> <div class="w-full text-gray-700 bg-white dark-mode:text-gray-200 dark-mode:bg-gray-800"> <div x-data="{ open: false }" class="flex flex-col max-w-screen-xl px-4 mx-auto md:items-center md:justify-between md:flex-row md:px-6 lg:px-8"> <div class="p-4 flex flex-row items-center justify-between"> <a href="{% url 'main' %}" class="text-lg font-semibold tracking-widest text-gray-900 uppercase rounded-lg dark-mode:text-white focus:outline-none focus:shadow-outline">Dummy Logo</a> <button class="md:hidden rounded-lg focus:outline-none focus:shadow-outline" @click="open = !open"> <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6"> <path x-show="!open" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 … -
convert string value to integer in Django template
In home.html <div class="container"> <div class="row"> <div class="col-md-6"> <h3>Select products:</h3> <form id="selectProduct" role="search" method="get" action="{% url 'home' %}"> <select name="parameters" data-placeholder="Choose products" class="chosen-select" multiple tabindex="4"> {% for p in productnames %} {% if k == p %} <option value="{{ p.productnames }}" selected> {{ p.productnames }} </option> {% else%} <option value="{{ p.id }}"> {{ p.productnames }} </option> {% endif %} {% endfor %} </select><br/> <label for="submit"></label><button id="submit" type="submit" class="btn btn-default">Submit</button> </form> </div> </div> <div class="row"></div><br /> <h3> Distribution of sales in the products:</h3> </div> </div> {% for p in productList %} {% for pin in productnames %} <p>{{pin.id}} {{p}}</p> {% if p == pin.id %} <p>exists</p> {% else %} <p>not exist</p> {% endif %} {% endfor %} {% endfor %} <p>{{ productList }}</p> in this html file 'p' always returns a string value for ex: it returns like '10' instead of 10. all i want is to convent this '10' to 10 or convert returned other p_in value to 10 to '10'. in views.py def productList(request): if request.method == 'GET': p = request.GET.get('parameters') print(p) #k = request.GET('parameters[]') productnames = Products.objects.all() context = { 'productList': p, 'productnames': productnames, } return render(request, 'home.html', context) I tried to convert the values of the p …