Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
from lxml import etree ImportError
from lxml import etree ImportError: Interpreter change detected - this module can only be loaded into one interpreter per process. I am getting this error after updating python from (3.4 to 3.8.0) and creating new environment for my django application. -
How to run python function from Django bootstrap Button
I was tring to understand the working of Django with the Bootstrap button. I was using one of the Django templates, in the index.html file, there is a button defined. <button type="submit" name="toggle" value="1" class="btn btn-primary btn-sm btn-round">Toggle</button> I defined a function in the view.py. @login_required(login_url="/login/") def mytoggletest(request): print("my toogle test script") print(request) and this is my urls.py urlpatterns = [ # The home page path('', views.index, name='home'), # my test path('/', views.mytoggletest, name='toggle'), # Matches any html file re_path(r'^.*\.*', views.pages, name='pages'), ] Now when I click on the toggle button in the html page nothing happens. How can I run my functions in the pythong files from button click on the page in django. -
why is CSS stylesheet partly not working in my Django app? Is it something to do with retrieving database data?
I believe I have all the Django settings correct as I have followed a few tutorials including a Linkedin one. I think I have identified where the problem occurs. The CSS stylesheet does work on my app everywhere except at the part of the code where I am retrieving postgres data.In addition when I modify the code and remove the postgres code the CSS will work and style that area. Therefore I don't understand why it stops working when I add the postgres! I have also included {% load static %} at the top of my HTML. I include my HTML the code below.. Code Snippet when it works: <div class="skills"> <h2>Stories!!!!</h2> <div class="skill-row"> <img class="princess-img" src="https://media.giphy.com/media/ZETg64fW7xb0gr4NEz/giphy.gif" alt="princess-img"> <h3><a href="Repunzel.html">Repunzel!!</a></h3> <p>Lets see hdewdow Repunzel manages to escape the tower, have an adbenture and finds out the truth!!.</p> </div> <div class="skill-row"> <img class="alladin-img" src="https://media.giphy.com/media/OoOvAC7vASedB6EhpS/giphy.gif" alt="alladin-img"> <h3><a href="Alladin.html">Alladin!!</a></h3> <p>Let's see if Kitty, Jasmine and Alladin manage with Genies' help to outsmart the baddies!!.</p> </div> </div> /When it doesn't work/ <div class="skills"> <h2>Stories!!!!</h2> {% for drawing in drawings.all %} <div class="skill-row"> <img class="{{drawing.classname}}" src="{{drawing.source}}" alt="{{drawing.classname}}"> <h3><a href="{% url 'detail' drawing.id %}" >Repunzel!!</a></h3> <p>{{ drawing.summary }}</p> </div> {% endfor %} </div> drawing is my … -
Why Django Rest serializer save doesn't work?
Example models: I have two models, posts and comments I want to save a comment with serializer, but it doesn't work class Post(models.Model): title = models.CharField(max_length=32) content = models.CharField(max_length=16) class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name="comments" ) title = models.CharField(max_length=32) comment = models.CharField(max_length=16) This is my serializer class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = [ 'title', 'comment' ] Like this I'm trying to do it # post instance serializer = CommentSerializer(post, data=comment_data) if serializer.is_valid(): # True serializer.save() It doesn't show any error, but don't save to the database. To solve I made a function that simulates serializer def save_c(post, comment_data): # this works # But I think it is better to use the serializer return Comment.objects.create(post=post, **comment_data) Any suggestion? I'll be very grateful -
Error while added djangorestframework-gis in view.py
I'm trying to create an API using bbox and I'm writing the function as per official doc of class LocationList(GenericAPIView): queryset = Transaction.objects.all() serializer_class = LocationSerializer bbox_filter_field = 'point' filter_backends = (InBBoxFilter,) bbox_filter_include_overlapping = True # Optional I have imported InBBoxFilter as follows from rest_framework_gis.filters import InBBoxFilter but I'm getting the following error File "/src/api/transaction/views.py", line 11, in <module> from rest_framework_gis.filters import InBBoxFilter File "/usr/local/lib/python3.8/site-packages/rest_framework_gis/filters.py", line 9, in <module> from rest_framework.filters import BaseFilterBackend File "/usr/local/lib/python3.8/site-packages/rest_framework/filters.py", line 11, in <module> from django.db.models.sql.constants import ORDER_PATTERN ImportError: cannot import name 'ORDER_PATTERN' from 'django.db.models.sql.constants' (/usr/local/lib/python3.8/site-packages/django/db/models/sql/constants.py) I tried following this https://www.gitmemory.com/issue/encode/django-rest-framework/7470/670721109 (using djangorestframework==3.11.1) but didn't work -
How to set different permission for different requests?
I want to have for post request permission only for authenticated users, for get request for all users and for patch and delete requests for moderator(one of the role which I put in models), admin and author Here is my views for Post: class CommentView(ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer permission_classes = [IsAuthenticatedOrReadOnly] def get_queryset(self): post = get_object_or_404(Post, pk=self.kwargs.get('post_id')) return post.comments def perform_create(self, serializer): post = get_object_or_404(Post, pk=self.kwargs.get('post_id')) serializer.save(author=self.request.user, post=post) Should I customize by myself permissions such as IsModerator, IsAuthor(Can't figure it out how to it for the author), and then afterwards write in generic views(get_query,perform_create,perform_update,perform_destroy) permission_classes=[..]? Or is there another solution for that problem? -
Howto do a LEFT JOIN in Django
Hello there (or as we say Moin Moin)! I am new to django development (version 2.0) and do not understand how to do a LEFT JOIN in django-syntax. For example I have the following models: class Units(models.Model): UnitID = models.AutoField(primary_key=True) Description = models.CharField(max_length=30) class MappingOperatorUnits(models.Model): OperatorID = models.ForeignKey(User, on_delete=models.CASCADE) UnitID = models.ForeignKey('Units', on_delete=models.CASCADE) class Participants(models.Model): UnitID = models.ForeignKey('Units', on_delete=models.CASCADE) LessonID = models.ForeignKey('Lessons', on_delete=models.CASCADE) OperatorID = models.ForeignKey(User, on_delete=models.PROTECT) NumberParticipants = models.SmallIntegerField() Now I am trying to do a query like SELECT * FROM MappingOperatorUnits LEFT JOIN Units ON ON MappingOperatorUnits.UnitID = Units.UnitID LEFT JOIN Participants ON MappingOperatorUnits.UnitID = Participants.UnitID and what I want to be the result is something like this: +-------------------+-----------------------+---------------------------------+ | Units.Description | Participants.LessonID | Participants.NumberParticipants | +-------------------+-----------------------+---------------------------------+ | TeamA | 1 | 0 | +-------------------+-----------------------+---------------------------------+ | TeamB | 1 | 3 | +-------------------+-----------------------+---------------------------------+ | TeamC | 1 | NULL | +-------------------+-----------------------+---------------------------------+ | TeamA | 2 | 2 | +-------------------+-----------------------+---------------------------------+ | TeamB | 2 | 5 | +-------------------+-----------------------+---------------------------------+ | TeamC | 2 | 1 | +-------------------+-----------------------+---------------------------------+ I tried a lot of things in manage.py's shell but din't come to the solution. Anybody can help me to get it? Thank you! -
Django server-side request forgery with fake host header
A have a Django app using the built-in settings called ALLOWED_HOSTS that whitelists request Host headers. This is needed as Django uses the Host header provided by the client to construct URLs in certain cases. ALLOWED_HOSTS=djangoapp.com,subdomain.djangoapp.com I made ten requests with a fake host header (let's call it fakehost.com) to the Django endpoint: /example. curl -i -s -k -X $'GET' \ -H $'Host: fakehost.com' -H $'Accept-Encoding: gzip, deflate' -H $'Accept: */*' -H $'Accept-Language: en' -H $'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36' -H $'Connection: close' \ $'https://subdomain.djangoapp.com/example' In the application logs I see the django.security.DisallowedHost error was raised ten times. However, according to the logs of fakehost.com, it did receive one request for /example. As I understand, this is a server-side request forgery (SSRF) vulnerability as the Django server can be made to make requests to an arbitrary URL. It makes debugging hard and is strange that the issue doesn't occur consistently. Also strange that the fake host seems to be recognised by Django, but one request still somehow reached fakehost.com. Does anyone have any ideas what I could investigate further in order to fix the apparent vulnerability in this Django app? Is the … -
How do i deploy a django website on SunOS 5.11?
I recently cobbled together a website for a friend of mine with Django, and I am trying to deploy it at the moment. I basically have no idea what I'm doing I feel like. At the moment I'm trying to deploy it to the Strato web space with WSGI and use gunicorn for this. According to the documentation (https://docs.gunicorn.org/en/latest/deploy.html) i have to install nginx. i have no package installer or admin access with sudo so i did this with wget and tar. when i try to configure nginx it says i have no c compiler to do this. So i tried to install gcc (again with wget and tar) but i need a c compiler to configure and make gcc? The OS that the Strato web space runs on is: SunOS hawkin 5.11 11.4.25.75.3 i86pc i386 i86pc Solaris My question: can any one point me to a decent tutorial for noobs on how to deploy a Django website on this UNIX distribution without admin access, or help me in configuring the web space and deploying the site? P.S. the Django website is programmed with python 3. if i check the usr/bin folder i can see a python3 folder, but the … -
Google maps satellite view footprints not congruent to street map view
I am trying to draw the layout of a building and project them to a web map using django and leaflet. I am using a satellite image to get the correct latitude and longitude and then I send the coordinates via an API. The process in short: Get lat/lon from a satellite image Send coordinates to webmap with SRID 4326 display the outlines My main problem with almost all my coordinates is that the google map satellite layer is not congruent to the street view. For example let's say I pinpoint lat: 50.11843503887959 and long 8.63194562490686 to google maps. I get the following image in satellite view: satellite_view Note that the point is exactly on the edge. But if I change the layer to the normal map view I get this result: map_view Note that the point is about 1cm to the right within the building. This happens to almost all buildings I am trying to pinpoint. Sometimes it's to the left and sometimes it's to the right. I read here https://gis.stackexchange.com/questions/48949/, that: Google Earth is in a Geographic coordinate system with the wgs84 datum. (EPSG: 4326) Google Maps is in a projected coordinate system that is based on the … -
Best practices for often repeating background tasks in django and pythonanywhere
So, I am currently working on a django project hosted at pythonanywhere, which includes a feature for notifications, while also receiving data externally from sensors through AWS. I have been thinking of the best practice in order to implement this. I currently have a simple implementation which is a view that checks all notifications and does the actions as needed if required, with an always-on task (which simply means a script that is running independently) sending a REST request to the server every minute. Server side: views.py: def checkNotifications(request): notificationsObject = notifications.objects.order_by('thing').values_list('thing').distinct() thingsList = list(notificationsObject) for thing in thingsList: valuesDic = returnAllField(thing) thingNotifications = notifications.objects.filter(thing=thing) #Do stuff for each notification urls: path('notifications/',views.checkNotifications,name="checkNotification") and the client just sents a GET request to my URL/notifications/. which works. Now, while researching I saw some other options such as the ones discussed here with django background tasks and/or celery: How to initialize repeating tasks using Django Background Tasks? Celery task best practices in Django/Python as well as some other options. My question is: Is there a benefit to moving from my first implementation to this one? The only benefit I can see directly is avoid abuse from another service trying to hit my URl … -
Create an api for post's comments
I want to get by api the comments for the post, but there is a mistake in my code, can't figure it out how to solve this? So here is my models: class Post(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField("date published", auto_now_add=True) description = models.TextField(blank=True) class Comment(models.Model): text = models.TextField(blank=False) author = models.ForeignKey(User,on_delete=models.CASCADE) pub_date = models.DateTimeField("date", auto_now_add=True) serializers: class PostSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Post class CommentSerializer(serializers.ModelSerializer): author = serializers.SlugRelatedField(read_only=True,slug_field='username') class Meta: fields = ('id','text','author', 'pub_date') model = Comment views: class PostView(ModelViewSet): queryset = Post.objects.all() serializer = PostSerializer class CommentView(ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer def get_queryset(self): post = get_object_or_404(Post, pk=self.kwargs.get('post_id')) return post.comments def perform_create(self, serializer): post = get_object_or_404(Post, pk=self.kwargs.get('post_id')) serializer.save(author=self.request.user, post=post) urls: router_v1 = DefaultRouter() router_v1.register('posts', PostView) router_v1.register('posts/(?P<post_id>[0-9]+)/comments', CommentView) -
Ajax problem when browsing with domain name
I have a Django website hosted under AWS/Cloudfront. Every form contains a CSRF token and is caught with jquery and then processed with AJAX. When accessing the website with the Elastic Beanstalk URL everything works fine. Url pattern working: http://example.us-east-2.elasticbeanstalk.com When accessing the website with the domain name, all the Ajax calls are refused with a 403 error. Url pattern not working: https://www.example.com/ I have the strong intuition there is a parameter to change in AWS, but for me, it is a black-box. Thank you in advance for reading and maybe answering this. -
Django - Pass data from javascript to view & redirect to a new url
On my webpage there are 2 buttons - A & B. I want to capture the button clicked by the user in front end & send it back to the server so that I can generate the appropriate token for the user. Then redirect the user to the right url - "/A" or "/B" depending on what they clicked. urls.py path('buttonTest/', buttonView), # Initially testing with one url Views.py def buttonView(requests): if requests.method == 'POST': clicked_button_val = requests.POST.get('clicked_button') # generate auth token render(requests, 'test.html') test.html <form id="testform"> <button name="subject" id="A" type="submit" value="A">A</button> <button name="subject" id="B" type="submit" value="B">B</button> </form> <script> $("button").click(function() { $.ajax({ type: "POST", data: { "clicked_button": $(this).val(), }, success: function(result) { alert('ok'); }, error: function(result) { alert('error'); } }); }); </script> I am able to successfully pass the data from front-end to views. But the url doesn't redirect to /buttonTest. If I add redirect in html like this, <button name="subject" id="A" type="submit" value="A" onclick="location.href='/buttonTest'">A</button> then the request in views.py becomes a GET request & is not able to access what the user clicked. What I want to do is capture the button clicked by user via a POST request & then redirect the user to a new url & … -
After uploading file, How to update table (which is linked with JavaScripts) using AJAX in Django?
Before uploading the file the table looks like this: After uploading the file using AJAX, the table needs to refresh using AJAX(Which is linked with some scripts tag): Note: The main problem here is after the AJAX success request, the JavaScripts not applying for the tabledata container. In views.py: @login_required(login_url='/login/') def upload_csv(request): form = CsvfileForm(request.POST or None, request.FILES or None) if form.is_valid(): user = form.save(commit=False) user.author = request.user user.file_id = ("FILE" + (uuid.uuid4().hex[:9]).lower()) user.save() form = CsvfileForm() obj = CsvFiles.objects.get(Q(activated=False) & Q(on_process=False)) obj.on_process=True obj.save() with open(obj.file_name.path,'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i==0: pass else: csvdatas.objects.create( file_link = obj, file_id=obj.file_id, author = request.user, data_id=("ABC"+(uuid.uuid4().hex[:9]).lower()), year=row[0], industry_code=row[1], industry_name=row[2], rme_size=row[3], variable=row[4], value=row[5], unit=row[6] ) obj.activated = True obj.save() all_datas = csvdatas.objects.filter(author=request.user) all_table = CsvFiles.objects.filter(author=request.user) return render(request,'refreshTable.html',locals()) In RefreshTable.html: <legend>Datas</legend> <br> <div id="alert-box1"></div> <br> <section id="file_table"> <table id="table_id1" class="display responsive nowrap" style="width=100%;"> <thead> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 1</th> <th>Download</th> <th>Delete</th> </tr> </thead> <tbody> {% for i in all_table %} <tr> <td>{{ i.file_id }}</td> <td>{{ i.file_name }}</td> <td>{{ i.uploaded }}</td> <td><a href="{{ i.file_name.url }}" target="_blank">Download</a></td> <td> <form method="post" action="{% url 'deletefile' i.pk %}" id="deleteid"> {% csrf_token %} <input type="submit" value="Delete" /> </form> </td> </tr> {% endfor %} … -
How to perform CRUD to embedded document with Django Rest Framework (Djongo and MongoDB)
I have used embedded approach for constructing django models namely productDetail, ShipmentDetails , Customer and Import.I am using django with djongo to create an API. Below is my models.py file. Are my models constructed correctly? from djongo import models from django import forms # Create your models here. class ProductDetail(models.Model): productName = models.CharField(max_length=70, blank=False) quantity = models.IntegerField(blank=False) netWeight = models.FloatField(max_length=70, default=False) price = models.IntegerField() class Meta: abstract = True class ProductDetailForm(forms.ModelForm): class Meta: model = ProductDetail fields = ( 'productName', 'quantity', 'netWeight', 'price' ) class ShipmentDetails(models.Model): blNo = models.CharField(max_length=100) shipDate = models.DateField() vesselName = models.CharField(max_length=70) vesselType = models.CharField(max_length=70) load = models.FloatField() class Meta: abstract = True class ShipmentDetailsForm(forms.ModelForm): class Meta: model = ShipmentDetails fields = ( 'blNo', 'shipDate', 'vesselName', 'vesselType', 'load' ) class Customer(models.Model): customerName = models.CharField(max_length=70, default="anything", null=True) class Meta: abstract = True class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'customerName', ) class Import(models.Model): productDetails = models.EmbeddedField( model_container=ProductDetail, model_form_class=ProductDetailForm ) indenter = models.EmbeddedField( model_container=Customer, model_form_class=CustomerForm ) partners = models.EmbeddedField( model_container=Customer, model_form_class=CustomerForm ) exporter = models.EmbeddedField( model_container=Customer, model_form_class=CustomerForm ) shipmentDetails = models.EmbeddedField( model_container=ShipmentDetails, model_form_class=ShipmentDetailsForm ) Payment_options = ( ('C', 'Cash'), ('CD', 'Card'), ) Status_options = ( ('S', 'Signed'), ('US', 'Unsigned'), ('P', 'Pending'), ) dealDate = models.DateField() departureDate … -
start 'forloop.counter' from different index or add something to the result
basically i want to count the iteration and end few tags after every 4th block and 1st block is put manually so therefore the forloop.counter wont get the work done either I need to make the count start from 4 or just add 2 to the result {% forloop.counter + 2%} but add like this throws error Unused '+2' at end of if expression I am new to Django how do I do this -
serialize text field to json
a third-party application I am using is storing json in a textfield. I would like to serialize this data to json, and I only need to be able to read from this serializer, not write to it. I don't want to have to manipulate the data on the frontend, so I want it to come out at clean json from my api. class SomeSerializer(serializers.ModelSerializer): details = serializers.CharField() class Meta: model = SomeModel fields = ( 'id', 'details') right now this is returning: [{"id":"someID", "details":"{\"address\": {\"city\": null}"}"}] I can't figure out how to use json.loads in a serializer, which would seem the cleanest option. -
MultiValueDictKeyError at /form 'name1'
I am new at django I was designing my own website to store value of form in the database please help I can't able to overcome the error the error is multivaluedicterror from django.shortcuts import render from django.http import HttpResponse from main.models import recieve_content # Create your views here. def index(request): return render(request,'index.html') def about(request): return render(request,'about.html') def contact(request): return render(request,'contact.html') def donation(request): return render(request,'donation.html') def form(request): if request.method=="POST": name1=request.POST["name1"] name2=request.POST["name2"] address=request.POST["address"] content=request.POST["content"] data=recieve_content(fname=name1,lname=name2,address=address,content=content) data.save() return HttpResponse("your data saved successfully") return render(request,'form.html') -
how can i solve this error in my code? TypeError: argument of type 'function' is not iterable
I'm trying to make a search function that on entering the query takes to the required result page. But it's showing this error: TypeError: argument of type 'function' is not iterable this my view.py code : def search_result(request): entryList = util.list_entries query = request.GET.get('q') query_str = str(query) if query in entryList: query_found = True return render(request,"encyclopedia\search_result.html",{ "query_found": query_found, "title": query, "content": util.get_entries(query) }) else: query_found = False return render(request,"encyclopedia\search_result.html",{ "query_found": query_found, "title": query, "search_reasult_list": entryList }) -
OAuth2 Authentication server users
I'm not good at explaining my issue, but I will do my best, As I need the help. I have an authentication and a resource server and I want my customers and company details from the authentication server to be on the resource server as well. I use django-oauth-toolkit, and during introspection username of the access token owner is saved on the resource server which is not enough. I tried and searched for solutions to this issue but to no avail. Now I'm thinking of sending a "POST" request with the customer and company details when they are registered. Is this a good idea? or should I look for another solution? -
javascript checksum encoding to python
can anyone help me translate this encoding in javascript to python as i'm trying to convert it to python. there are 4 lines at the bottom that i'm trying to understand step by step and if you could give me values that you get line by line for those 4 lines that will be great help. In the best case scenario if you can just convert the calcultation into a python script with the vars provided, thank you so much for the help. var data = { categoryId: 8, equipmentState: 'NEW', equipmentType: 'PRODUCT', image: 'https://bigcorp.com/product.jpg', link: 'https://bigcorp.com/product.html', model: 'NICE PRODUCT', priceInCts: 437700, cashPriceInCts: 450700, reference: 'REFERENCE-123456', shippingDeliveryTimeInDays: 7, shippingType: 'HOME_DELIVERY', shippingUnitaryCostInCts: 3900, trademark: 'BIGCORP' }; var vars = [ data['categoryId'], data['equipmentState'], data['equipmentType'], data['image'], data['link'], data['model'], data['priceInCts'], data['cashPriceInCts'], data['reference'], data['shippingDeliveryTimeInDays'], data['shippingType'], data['shippingUnitaryCostInCts'], data['trademark'] ]; var token = 'TOKEN'; var buffer = Buffer.from(token, "hex"); var hmac = crypto.createHmac('sha512', buffer); var data = hmac.update(vars.join('&')); var checksum = data.digest("hex").toUpperCase(); -
Setting DATABASE_URL in django cookie-cutter application for github ci during pytests?
I uploaded the raw django cookie-cutter code to master in a repo on github. I made a second branch with some changes and tried to merge it with master and got errors it seems the ci had a docker container and it's running tests before it merges (Love that, BTW. Thanks to github for putting in docker to run tests and django cookie-cutter to take advantage of it.). docker-compose -f local.yml exec -T django pytest The problem is the DATABASE_URL isn't set. Is there something that I need to put in order to run the entrypoint file (which has the DATABASE_URL set)? or what is the most natural way to give github that variable to fix that since the database will be running in a github docker service? -
How do I call a static image from the CSS of an element with Django?
I used bootstrap studio to make a simple frontend page and I'm learning django so I'm using a bootstrap frontend for the app. All the static resources are in a static folder that i call using: {% load static %} And the image is at: static 'img/map.png' In the below code, the div is calling the background image using css - background:url('assets/img/map.png') But of course this wont work because I have a folder called static with the static assets <div class="col" style="text-align: center;display: flex;justify-content: center;align-items: center;flex-flow: column;min-width: 300px;background: url('assets/img/map.png');background-size: cover;"> <div style="background: rgba(255,255,255,0.85);margin-top: 66px;margin-bottom: 66px;"> <h1>Diverse Locations</h1> </div> </div> Is there any way I can make the div point to the right background image? Note: I created the static folder by copying the static content into the project folder, defined the STATIC_ROOT and STATICFILES_DIRS variables and ran the command: python manage.py collectstatic. -
Django href for decrement and increment error for a django cart
I am working on my first django project. I am creating an ecommerce store and I encountered a problem that I do not know how to solve it. It is about a personalized cart where I am trying to increment and decrement products within the cart. urls.py urlpatterns = [ ....... path("cart/<int:id>/", views.increment, name="increment"), path("cart/<int:id>/", views.decrement, name="decrement"), path("cart/<int:pk>/", views.CartItemDelete.as_view(), name='cart_delete'), .....] views.py def increment(request, id): if request.method == "GET": item = UserItem.objects.get(pk=int(id)) if 0 < (item.quantity + 1) <= item.prod_id.quantity: item.quantity += 1 item.save() return redirect('cart') return redirect('cart') def decrement(request, id): if request.method == "GET": item = UserItem.objects.get(pk=int(id)) if 0 < (item.quantity - 1) <= item.prod_id.quantity: item.quantity -= 1 item.save() return redirect('cart') return redirect('cart') class CartItemDelete(DeleteView): model = UserItem template_name = "cart_delete.html" context_object_name = "crt" success_url = reverse_lazy("cart") templates <div class="card" id="cardDisplay"> <img class="card-img-top" src="{{ prd.img.url }}" alt="Card image" id="image_prod"> <div class="card-body"> <h4 class="card-title"> {{ prd.name }}</h4> <form action="{% url 'cart_qu' %}" method="get"> <label> Quantity: <input type="number" name="quantity" min="1" value="{{ prd.quantity }}" > <input type="hidden" name="{{ prd.pk }}"> </label> </form> <a href="{% url "increment" prd.pk %}"><button>+</button></a> <a href="{% url "decrement" prd.pk %}"><button>-</button></a><br> <a href="{% url 'cart_delete' prd.pk %}">Delete</a> <p class="card-text">Price: {{ prd.price }} lei <br> </div> My problem is that …