Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I delete ManyToManyField on Django Model (used in Wagtail Page inheritor)?
I have such field: from wagtail.models import Page class MyModel(Page): ... many_to_many_field = models.ManyToManyField(ToClass, blank=False, related_name='+', verbose_name=_("My models")) ... I tried simply to comment it like this: from wagtail.models import Page class MyModel(Page): ... # many_to_many_field = models.ManyToManyField(ToClass, blank=False, related_name='+', verbose_name=_("My models")) But I've got 'django.core.exceptions.FieldError' while was executing 'python manage.py makemigrations': Traceback (most recent call last): File "D:\projects\myapp\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "D:\Python311\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Python311\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 443, in execute self.check() File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 475, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\checks.py", line 70, in get_form_class_check if not issubclass(edit_handler.get_form_class(), WagtailAdminPageForm): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\panels\base.py", line 162, in get_form_class return get_form_for_model( ^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\panels\base.py", line 48, in get_form_for_model return metaclass(class_name, tuple(bases), form_class_attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\forms\models.py", line 124, in __new__ new_class = super(WagtailAdminModelFormMetaclass, cls).__new__( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ new_class = super().__new__(mcs, name, bases, attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\modelcluster\forms.py", line 259, in __new__ new_class = super().__new__(cls, name, bases, attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\django\forms\models.py", line 327, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (many_to_many_field) specified for MyModel What is wrong? How can I delete it? -
post name, email and role in django backend, react frontend
i want to the admin to post name, email and role of a user using frontend, and its stored in backend of django, please note that i dont want the admin to store the password, the user will later on add it djangocode: class UserSerializer(serializers.ModelSerializer): class Meta: model = UserAccount fields = ['email', 'name', 'username', 'password', 'role'] def create(self, validated_data): password = validated_data('password') username = validated_data('username') user = UserAccount( email=validated_data['email'], role=validated_data['role'], name=validated_data['name'] ) if username is not None: username=validated_data['username'], if password is not None: user.set_password(validated_data['password']) user.save() return user react code: const handleSubmit = (event) => { event.preventDefault(); const data = { name : name, email : email, role: role }; console.log("data is "+data); axios.post('http://127.0.0.1:8000/api/register/', data) .then(response => console.log("got it"+response.data)) .catch(error => console.log(error)); console.log('name:', name); console.log('email:', email); console.log('role:', role); -
How to store an object id in django admin
I got a top model like Project, and many sub models like Store, Task, Bug, TestCase. I want to seprate project as isolated workspace in admin. when I select a project, store the current project id, and when I create sub model objects or view change list, all object is belong to this project. -
Unable to read django table in admin or through API
I've added few tables to django app, and two of them are acting weird. I'm unable to read these 2 tables through django admin or postman API however, I'm able to read these table through postgres(pg admin). I'm getting index error in django-admin and postman on these two tables(or django models). These tables has data in them as verified using pgAdmin. The tables are stored in postgres, and the DB is connected to django aplication. Any idea why this could be happening and possible solutions? -
Bad Request (400) on adding new domain from hostinger on vercel hosting
I have purchased domain from hostinger after adding the domain in the domain and changing the nameserver of hostinger to ns1.vercel-dns.com ns2.vercel-dns.com i validated the configuration but when i look the site it gives Bad Request (400) error . pushpblogs.fun Valid Configuration Redirects to www.pushpblogs.fun www.pushpblogs.fun Production Valid Configuration Assigned to main i waited for the dns to apply for 24 hours but still no change made. -
Mayan EDMS ,Calling the API remotely using AJAX getting CORS error
I am creating a new webapp that is going to be making calls to the Mayan EDMS API with javascript/ajax Currently i am getting a CORS error. My mayan installation is running inside a docker container. I did find in the settings for Django in the admin->settings-> Django there is a ALLOWED_HOSTS but there is a green checkmark which indicates it is overwritten by a env var. Any Idea what env var that would be. there is nothing obvious in the .env for the docker file It appears that django-cors-headers is there as well. Just not sure how to config How are other people dealing with this? Thanks randy -
Python route usage
How can I use $ in the python url . This is my usage from django.urls import include, path from vote import views urlpatterns = [ path(r'^$', views.index, name='index') ] but it ending with Using the URLconf defined in election.urls, Django tried these URL patterns, in this order: [name='index'] vote/ ^$ [name='index'] I need to get understand what is the best usage -
(Python/Django) Can I use Python's Django framework w/o using templates?
I am learning how to use the Django framework, and as I am learning about Django's template system, I was wondering, if it would be possible for me to use Django without using templates to render the necessary html documents from views? As an alternative to Django's template system, I would prefer to use JavaScript in order to make the necessary data queries from the sites database(s). This might seem counter productive, but in my opinion, I would prefer to learn the traditional front-end web stack(HTML, CSS, JS), and solidify my skills this way before going down the journey of template systems. At this point, I would be using Django only as a back-end until I was ready to incorporate templates into my dev process. Thank you in advance! This my first post on SO, take it easy! I have tried to use Django's template system, but It's a little comprehensive to learn on top of HTML and CSS at the same time. -
Gives 404 error even when audio file exists: GET /data/audio/5dc18de4d34d12a20b21fbc2506b423f35cfd7fc0fc931874bdfe13b1578aeee.m4a HTTP/1.1" 404 179
enter image description here The file is present and still gives a 404 and works on other machine perfectly fine. It is an audio file which is saved inside data/audio and that is where the local is trying to search which is correct location but still gives 404 -
DJango how to manage redshift connection in a server
I am using redshift in my django application. I know we can use psycopg2 for redshift, but i am planning to use the aws library pip install redshift_connector Currently for every query in my view i run. So here I see its taking time to connect to redshift everytime and thats consuming time than then query time. conn = redshift_connector.connect( host='host.docker.internal', database='dev', port=5439, user='user', password='kkshdjhjhsdj' ) cursor = conn.cursor() cursor.execute("SELECT CURRENT_TIMESTAMP") data = cursor.fetchall() I am not sure how django keeps connection live for database and effeciently handle. If we have to use some thirdparty databases then how to handle connection. Can someone guide me what else needs to be taken care. -
Django template: how to show decimal value as currency format with dollar sign, thousand separator with zero or two decimal points
The field in models.py is: order_amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) if the order_amount value is 12345.67, how to display it in Django template for the below two formats: without decimal point: $12,345 without two decimal points: $12,345 -
Am getting empty strings in my django database when trying to save JSON data from ajax request
Am new in coding skills so am creating a website now am stuck , in my website users answer a question by clicking one button choice out of many button choices , i want when a button is clicked data to be sent to the django database but unfortunately when i click the button only empty strings is sent to the database views.py import json from django.http import JsonResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.urls import reverse from .models import JasonData from .form import QuestionForm # Create your views here. def index(request): """The homepage for Stay_healthy""" return render(request, 'Stay_healthy/index.html') def redirect_to_index(request): """The homepage for Stay_healthy""" return HttpResponseRedirect(reverse('index', args=None)) def json_data_store(request): if request.method == 'POST': # this runs incase the request is an ajax if request.headers.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': data = json.loads(request.body) form = QuestionForm(data) if form.is_valid(): form.save() return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'error'}) else: # this runs incase the request is not ajax form = QuestionForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = QuestionForm() return render(request, 'Stay_healthy/question_detail.html', {'form': form}) def check_data(request): stored_data = JasonData.objects.all() return render(request, 'Stay_healthy/check_data.html', {'stored_data': stored_data}) models.py from django.db import models # Create your models here. class JasonData(models.Model): patient_data = models.JSONField(blank=True, null=True, default=dict) form.py … -
How to send multiple objects on serializers.Serializer (got non_field_errors)
I'm trying to send multiple data through a create viewset method to a serializer. However when doing that I get an error as follows: enter image description here Im using many attribute into the serializer, but I sill get the same error. I'm posting data like this: [ { "weekday":"day", "start_time":"time", "end_time":"time" }, { "weekday":"day", "start_time":"time", "end_time":"time" } ] This is the viewset and serializer code: viewset.py class SpecialistAvailabilityView(viewsets.ModelViewSet): model = SpecialistAvailability permission_classes = [IsAuthenticated, IsSpecialist] def get_serializer_class(self): saving_actions = ["create", "update", "partial_update"] if self.action in saving_actions: return WeekDayTimeSerializer return SpecialistAvailabilitySerializer def get_queryset(self): queryset = SpecialistAvailability.objects.filter( specialist__user=self.request.user ).order_by('-start_time__week_day') return queryset def translate_availability(self, data): pass def create(self, request, *args, **kwargs): serializer = WeekDayTimeSerializer(data=request.data, many=isinstance(request.data, list)) print(serializer.initial_data) print(serializer.is_valid()) if serializer.is_valid(): self.translate_availability(serializer.validated_data) return super().create(request, *args, **kwargs) serializer.py import pytz from datetime import datetime from rest_framework import serializers from apps.specialist.models.specialist_availability import SpecialistAvailability from apps.specialist.utils import WEEKDAYS class WeekDayTimeSerializer(serializers.Serializer): weekday = serializers.ChoiceField(choices=WEEKDAYS, required=True) start_time = serializers.TimeField() end_time = serializers.TimeField() # TODO ADD TIME AND WEEKDAY CHECKING # START TIME MUST BE LESS THAN END TIME # JUST ONE DAY MUST BE SENDED IF MANY def validate(self, attrs): self.validate_start_time(attrs['start_time']) self.validate_start_time(attrs['end_time']) self.validate_end_time return super().validate(attrs) def validate_start_time(self, start_time): try: datetime.strptime(start_time, "%H:%M") except: raise serializers.ValidationError("Wrong time format") return start_time … -
Django payment intigration
i want to add a donation page in my DJango project but i have not seen any proper intigration of payment gateway in any articles and videos so plzz help me and give the proper code and explanation. in stripe apy key is not supported in india in razorpay when click on payment error occur amount exceed -
django rest framework: Getting "This field may not be null." with FloatField even with blank=True
Here dummy code to show my problem: In my django models.py I have something like: class MyModel(Model): test_field = SlugField(blank=True, null=False) # some other not-null not-blank fields here def save(self, *args, **kwargs): self.test_field = .... # Setting with a value calculated form the other not-null not-blank fields Here my serializer: from rest_framework import serializers class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = [ ...., 'test_field', ] In my views.py something like: def post_endpoint(request): data = JSONParser().parse(request) serializer = MyModelSerializer(data=data) if serializer.is_valid(): .... serializer.save() return JsonResponse(serializer.data, status=201) This is working as expected: I can send an object to my post_endpoint without my test_field and I get my result with test_field set as expected. serializer.is_valid() returns True in that case. The problem? I need that same functionality but with a FloatField instead of SlugField. But I noticed serializer.is_valid() returns False in that case and I get a "This field may not be null." in serializer.errors in my view function. How is FloatField different from SlugField ? How can I get the expected functionality also with FloatField? djangorestframework==3.14.0 Django==4.0.5 -
Browser not downloading request response, even though Content-Disposition is 'attachment' and Content-Type is 'text/plain'
I am under the impression that if Content-Disposition is set to 'attachment' and Content-Type is set to'text/plain', the browser should download the request response as a .txt, but when I make the request locally on my browser, a download is not initiated. On other pages, like https://textdoc.co/, my browser does download a similar request response, so it doesn't seem like a browser issue. On my server: from django.http import FileResponse ... with open('readme.txt', 'w') as f: f.write('Create a new text file!') response = FileResponse(open("readme.txt", "rb"), as_attachment=True, filename="test.txt") response['Content-Type'] = 'application/download' return response After making this request on my client I get the following results in the google chrome developer console: **Response Headers:** Access-control-allow-origin: http://localhost:3000 Allow: POST, OPTIONS Content-Disposition: attachment; filename="test.txt" Content-Length: 23 Content-Type: application/download Cross-Origin-Opener-Policy: same-origin Date: Thu, 08 Jun 2023 21:46:37 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.11.3 Vary: Accept, origin X-Content-Type-Options: nosniff X-Frame-Options: DENY **Response:** Create a new text file! I was expecting this request to cause the browser to prompt the user to download the file. However, the browser is not prompting the user. Here is an example of what the prompt looks like on Google Chrome: -
request.POST.get() is returning nothing
The problem is though I am putting correct data in the form, it always redirects to the except block of views.py I tried to change and refresh data in the database but didn't work out. Here is my views.py @login_required(login_url='login') def card_payment(request): card_no = request.POST.get('cardNumber') pay_method = 'Debit card' MM = request.POST['MM'] YY = request.POST['YY'] CVV = request.POST['cvv'] request.session['dcard'] = card_no try: balance = Cards.objects.get(Card_number=card_no, Ex_month=MM, Ex_Year=YY, CVV=CVV).Balance request.session['total_balance'] = balance mail1 = Cards.objects.get(Card_number=card_no, Ex_month=MM, Ex_Year=YY, CVV=CVV).email if int(balance) >= int(request.session['pay_amount']): # print("if ma gayu") rno = random.randint(100000, 999999) request.session['OTP'] = rno amt = request.session['pay_amount'] username = request.user.get_username() print(username) user = User.objects.get(username=username) mail_id = user.email print([mail_id]) msg = 'Your OTP For Payment of ৳' + str(amt) + ' is ' + str(rno) # print(msg) # print([mail_id]) # print(amt) send_mail('OTP for Debit card Payment', msg, 'nafibinnoor@gmail.com', [mail_id], fail_silently=False) return render(request, 'OTP.html') return render(request, 'wrongdata.html') except: return render(request, 'wrongdata.html') HTML form for this view <form action="pessanger_detail_def/card_payment" method="POST" class="creditly-card-form agileinfo_form"> {% csrf_token %} <section class="creditly-wrapper wthree, w3_agileits_wrapper"> <!--<label>Name On Card</label></br> <input type="text" class="pipo1" placeholder="John smith" name="name"></br>--> <label>Card Number</label> <input type="text" class="pipo1" placeholder="**** **** **** *****" name="cardNumber"></br> <label>CVV</label></br> <input type="text" class="pipo1" placeholder="***" name="cvv"><br> <label>Expiration Date</label></br> <input type="text" class="pipo2" placeholder="MM" name="MM"><label> </label><input type="text" class="pipo2" placeholder="YY" … -
Trying to write a django query to count different rows and find the max value
I have a django app that stores documents (photos, pdfs, video, ect.) as well as some metadata (year, decade, etc.). The metadata is stored in a JSONField called metadata in a model called DocumentMetaData. I would like to create a django query that allows me to find the maximum number of documents for a certain metadata name. For example, all documents have in their metadata field a "Decade" value. I can loop through all the decades to find the decade with the most documents, like this: decades = ['1860', '1870', '1890', '1900', '1910', '1920', '1930', '1940', '1950', '1960', '1970', '1980', '1990', '2000','2010', '2020'] max_count = 0 max_decade = "" for decade in decades: count = DocumentMetaData.objects.filter(metadata__has_key='Decade').filter(metadata__Decade=decade).count() if count > max_count: max_count = count max_decade = decade Can I replace this code with a django query using annotate and aggregate? I am just not seeing how to create a query with a loop in it. Thanks! -
Workbox service worker only registering routes when CORS is turned off
I have a django/react app that is trying to use a service worker to allow precaching and offline operations. Specifically, I am using Workbox. It's actually working fairly well, except the ability to work offline. The service worker's file is located, the service worker installs without issue, and even precaches all necessary files. When I start in a chrome browser with all history/cache emptied, it starts up decently Service worker is installed on application tab: Manifest is present on the application tab And we even have precached files on the application tab. There is a log in the console from workbox that says six files are precached However, if we reload the page (which is necessary to get the routing) Workbox does not detect any routes And it doesn't work when you set it to offline in the network tab HOWEVER, if I disable web security/CORS in chrome with this command "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir=%LOCALAPPDATA%\Google\chromeTemp Everything else works the same, just the registering of routes and offline operations works fine. The service worker starts, installs, and precaches the same. The manifest is detected. But, on second load, the console logs that workbox has routes, and that they match the requests. … -
Django, how to do two-factor authorization via email?
I have a website and I have already redefined the user model, made authorization/registration via email. Now I want to do authorization when a user enters a username, password and a confirmation code is sent to his email. I am interested in the scheme of work. I see it this way: vyushka generates code using random, send_email sends it and this very code is written to the database. In my opinion, this is a bad decision (For example, to store the code in the database with the user, because you still have to implement the expiration date, etc.). So, are there any options for how this can be done. (generate code, where and how to store it for verification). I know about all sorts of libraries with 2FA, this is not my option. -
Django channel web socket to console.log() to the Browser
I am using npm wscat package to to send the message to django channels, when the message is sent through the terminal, it prints on the server console as expected, how ever when I send it to the browser the console is not logging the message following is my working code: #consumer.py from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): message_content = text_data print(message_content) self.send(text_data=message_content) #routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/$', consumers.ChatConsumer.as_asgi()), ] #index.html ... <script> let chat = null; function connect() { chat = new WebSocket("ws://localhost:8000/ws/chat/") chat.onopen = function (e) { console.log("Successfully connected to the WebSocket."); } chat.onmessage = function (result) { console.log(result.data); } chat.onerror = function (err) { console.log("WebSocket encountered an error: " + err.message); console.log("Closing the socket."); } chat.onclose = function (event) { console.log('WebSocket connection closed.'); }; <!-- --> } connect(); </script> ... In the brower chat.onopen function works perfectly, and is diplayed in the browser, however for some reason chat.onmessage function never gets executed. -
How call an API from Django before creating an object
I'm currently learning the Django framework, and I have a Account model. I want to retrieve data from an external REST API to populate the fields of this model. Here's an example: class Account(models.Model): external_id = models.CharField(max_length=60) account_id = models.CharField(max_length=60) puuid = models.CharField(max_length=85) name = models.CharField(max_length=20) def __str__(self) -> str: return "{} (id: {})".format(self.name, self.external_id) @classmethod def create(cls, nickname): # Here I would like to call the external API in order to recover some of those fields. account = cls(external_id = '', account_id = '', puuid = '', name = nickname) return account I can simply import the requests library here, make API calls, and it will work. However, I would like to know the correct way to do it. I assume that I should create a services.py file and implement the API call logic there, but I'm unable to find a style guide. Is there any convention? -
Can you side-load relations in a Django Rest Framework response?
I have an API endpoint that needs to return many thousands of results that share relations. I would like to return the ID on each result and then return a second set of data containing each of the relations (rather than repeating the relations on each result). What's the best way to go about side-loading relations? -
How can I add relation values to a serializer in Django Rest Framework?
I would like to return many thousands of results along with one attribute from a relation. I tried including the value in the fields array but got the following error: Field name checklist__location__latitude is not valid for model Sighting. Is there a way to add the latitude value to each sighting object? I'm cautious of adding too much overhead to the returned results (they could get very large, so I want the JSON to be as minimal as possible), and I don't want to iterate over every object to attach the value after retrieval from the database. -
Not getting specific object using foreign key relationship in django
I am facing an issue where iam trying to get an Egg item object by using foreign key relationship but it again and again show me this error "Some Error Occurred While Saving Data: Egg matching query does not exist." My models are: class SaleReturnItem(models.Model): salereturn = models.ForeignKey( SaleReturn, on_delete=models.CASCADE,related_name="salereturnitem" ) saleReturnItemName=models.ForeignKey(Egg, on_delete=models.CASCADE, related_name='salereturnitemegg',null=True) saleReturnItemQuantity=models.CharField(max_length=15,null=True) saleReturnItemUnitPrice=models.CharField(max_length=15,null=True) saleReturnItemTotalAmount=models.CharField(max_length=15,null=True) saleReturnItemDiscount=models.CharField(max_length=15,null=True) saleReturnItemDiscountPrice=models.CharField(max_length=15,null=True) class Egg(models.Model): user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE,default=1 ) eggName = models.TextField(null=True) eggInSection = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='eggsection',default=1) eggSalePrice = models.CharField(max_length=15,default=False) eggPurchasePrice = models.CharField(max_length=15,default=False) eggStockLimit = models.IntegerField(default=False) eggStockQuantity = models.IntegerField(default=False) eggInCategory = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='eggcategory',default=1) eggExpiryDate = models.DateField(blank=True, null=True) eggGst = models.DecimalField(max_digits=5, decimal_places=2,default=False) and my view function is this def saleReturn(request): if not request.user.is_authenticated: return redirect('login') elif request.user.userRole != 'admin': return render(request, 'pages/404.html') else: if request.method == "POST": try: searchSaleInvoiceId = request.POST.get('searchSaleInvoice') searchSaleInvoice = SaleInvoice.objects.get(id=searchSaleInvoiceId) invoiceDateSaleReturn = request.POST.get('invoiceDateSaleReturn') saleReturnObject = SaleReturn( user=request.user, searchSaleInvoice=searchSaleInvoice, invoiceDateSaleReturn=invoiceDateSaleReturn, ) saleReturnObject.invoiceDateSaleReturn = date.today() saleReturnObject.save() print("saleReturnObject",saleReturnObject) saleReturnItemNameId = request.POST.get('saleReturnItemName') saleReturnItem = Egg.objects.get(eggName=saleReturnItemNameId) print("-----------------1----------------------") saleReturnItemNameId = saleReturnItem.id saleReturnItemQuantity = request.POST.getlist('saleReturnItemQuantity') saleReturnItemUnitPrice = request.POST.getlist('saleReturnItemUnitPrice') saleReturnItemDiscount = request.POST.getlist('saleReturnItemDiscount') totalSaleAmountSaleReturn = 0.0 saleInvoiceAmountSaleReturn = 0.0 saleInvoiceDiscountSaleReturn = 0.0 for saleReturnItemNameId,quantity, price, discount, in zip(saleReturnItemNameIds, saleReturnItemQuantity, saleReturnItemUnitPrice, saleReturnItemDiscount ): saleReturnItemName = next(item for item in saleReturnItemNames if item.id == int(saleReturnItemNameId)) total_amount = int(quantity) * …