Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoSuchKey error while using digitalocean spaces and django-filebrowser-no-grappelli
I'm using django-filebrowser with DigitalOcean Spaces as the storage backend for my Django project. When I try to access the filebrowser URL to browse the files, I get the following error: NoSuchKey at /admin/filebrowser/browse/ An error occurred (NoSuchKey) when calling the ListObjects operation: Unknown I'm not sure what's causing this error and how to fix it. I've already checked the bucket name, region name, and permissions, but the error still persists. Here are some more details about my configuration: I'm using django-filebrowser version 3.12.2 and django-storages version 1.11.1. I have to set up the DEFAULT_FILE_STORAGE setting in my Django settings file to use custom-made storage class: import os from filebrowser.storage import S3BotoStorageMixin from storages.backends.s3boto3 import S3Boto3Storage class MyStorage(S3Boto3Storage, S3BotoStorageMixin): def _clean_name(self, name): return os.path.join("", os.path.normpath(name).replace('\\', '/')) def isdir(self, name): return name.endswith('/') I've set up the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_STORAGE_BUCKET_NAME, AWS_S3_REGION_NAME, and AWS_S3_ENDPOINT_URL settings in my Django settings file to configure the S3 connection to DigitalOcean Spaces. I've granted the s3:ListBucket and s3:GetObject permissions to the IAM user that I'm using to access the bucket (file uploading from admin panel is working fine) I've set up the MEDIA_URL setting in my Django settings file to point to the public URL of the … -
Django AttributeError: type object 'Admin' has no attribute '_meta' error when creating custom user
I'm learning django and I want to have my custom user and admin object but I'm encountering an error when running server after applying my changes. I'm not sure if this is the right approach to do this so do enlighten me if I'm following the wrong approach. So I have created an app called 'core' where I want to do authentication stuff so that's where I've put my custom user models. Here are the files I've written for that task so far: models.py: from django.db import models from store.models import CartItem from django.contrib.auth.models import AbstractBaseUser, UserManager from enum import Enum from django_countries.fields import CountryField from django.contrib import admin ADDRESS_CHOICES = ( ('B', 'Billing'), ('S', 'Shipping'), ) class AuthLevel(Enum): NONE = 0 Customer = 1 Admin = 2 Programmer = 3 class Address(models.Model): street_address = models.CharField(max_length=100) apartment_address = models.CharField(max_length=100) country = CountryField(multiple=False) zip = models.CharField(max_length=100) address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES) default = models.BooleanField(default=False) def __str__(self): return self.street_address.name + " " + self.apartment_address.name class Meta: verbose_name_plural = 'Addresses' class BaseUser(AbstractBaseUser): name = models.CharField(max_length=100, unique=True) auth_level = AuthLevel.NONE class Customer(AbstractBaseUser): username = models.CharField(max_length=100, unique=True) email = models.EmailField() address = models.OneToOneField(Address, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=50, blank=True, null=True) one_click_purchasing = models.BooleanField(default=False) cart = models.ManyToManyField(CartItem) #on_delete=models.CASCADE) … -
tmp file write pdf file google app engine django
I am using fpdf package for creating PDF in django. My file structure is project - contain all the setting files. apps - contain all the apps folders like apps/account/views.py apps/profile/views.py static - static files templage - all the template tmp class PdfCreater(View): def get(self, request, *args, **kwargs): pdf = FPDF('P', 'mm', 'Letter') pdf.add_page() pdf.set_font('helvetica', 'BIU', 16) pdf.set_text_color(220,50,50) pdf.cell(100, 80, 'Hello World jaskaran singh!' ) pdf.set_font('times', '', 12) pdf.cell(80, 10, 'Good Bye World!') path = str(settings.XYZ) pdf.output( path+ '/tmp/pdf_2.pdf') data = 'try' return JsonResponse({"data": str(path), "header": data}) now i am wring this code but my pdf_2.pdf file is not create in tmp folder why? In my localhost file has been create successfully but not in google app engine -
Adding Path Prefix for Django
I am using Digital Ocean's app platform so I don't really have access to an Nginx instance as they handle the routing etc. on their end. I have a frontend React app at: http://subdomain.domain.com And I have the backend Django app at: http://subdomain.domain.com/backend The Django app wasn't designed to have the leading prefix, so admin and site URLs look like this locally: http://0.0.0.0:8000/dashboard/sign-in http://0.0.0.0:8000/admin/login/ My URLs look like: urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', include(('dashboard.urls', 'dashboard'))), path('', include(('core.urls', 'core'))) ] When I visit the dashboard URLs, for example: http://subdomain.domain.com/backend/dashboard/home It works fine. I had to modify some of the redirects so that it would redirect to the right URL in the code, but it works fine. My issue is with the Django admin. When I manually visit lets say: http://subdomain.domain.com/backend/admin/login/ It will load the login View, but when I login/submit the form, it posts to the URL without the backend prefix. Also, if I login using my own form then navigate to the admin site, all of the links look absolute like: <a href="/admin/whatever"><a/> so when I click them it won't work. I looked into FORCE_SCRIPT_NAME, but when I use that and set it to something like backend it just … -
Not Found: /users/
I keep getting this error even though I have pathed it correctly. Can someone help me? Thanks. this is my form action url form method="post" action="/users/" id="archive-form" this is my javascript fetch url fetch("/users/", { this is my urls.py path url path("users/", views.users, name="users"), this is my views.py def users(request): active_users = User.objects.filter(status='active') archive_users = User.objects.filter(status='archived') user_form = UserForm() if request.method == 'POST': user_form = UserForm(request.POST, request.FILES) if user_form.is_valid(): user = user_form.save(commit=False) user.save() # log_message = f"Added user with ID {user.id}" Log.objects.create(user=user.first_name, role=user.job_title, date=timezone.now(), action=log_message) # return redirect('app:users') print('1') user_id = request.POST.get('user_id') user = get_object_or_404(User, id=user_id) if user: if user.status == 'active': user.status = 'archived' log_message = f"Archived user with ID {user_id}" elif user.status == 'archived': user.status = 'active' log_message = f"Unarchived user with ID {user_id}" user.save() Log.objects.create(user=user.first_name, role=user.job_title, date=timezone.now(), action=log_message) return redirect('app:users') -
Django custom login form does not validate
I have implemented a custom user model in my django project. I can use it to register a user however I cannot use it to login. It fails to validate against the is_valid() function. I have been able to confirm the email & password values are being passed through to views.py but the form is not being validated Here is my login view code def login_view(request): context = {} if request.POST: form = UserLoginForm(data = request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] print(email) print(password) user = authenticate(request, email=email,password=password) print(user) if user is not None: login(request,user) return redirect("logistics:dashboard") else: print('form not valid') form = UserLoginForm() context["loginform"] = form return render(request, 'dashboard/authentication-login.html', context) This is login form code class UserLoginForm(forms.ModelForm): password = forms.CharField(label="Password", widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'password') widgets = { 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'password': forms.PasswordInput(attrs={'class': 'form-control'}), } def clean(self): if self.is_valid(): email = self.clean_data['email'] pasword = self.clean_data['password'] if not authenticate(email=email, pasword=pasword): raise forms.ValidationError("Invalid Credentials") This is my custom user model class CustomAccountManager(BaseUserManager): def create_superuser(self,email, user_name, first_name, last_name, phone, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: … -
QR scanner does not show in dialog box pop out
Using vue.js and element-ui html, I have a table of records, which after clicking on the row, there is supposed to be a QR scanner dialog box pop out. Right now, the the dialog box does pop out upon clicking a row on the table but the QR scanner does not appear. I have tried many methods but it still does not seem to work. Hope someone can advice me on this. Thank you. <doctor_emr.html> {% load static %} {% block mainbody %} {% verbatim %} <div id="app2" class="container"> <div class="emr-table"> <el-table :data="list" @row-click="showQRScanner"> <el-table-column prop="id" label="ID"></el-table-column> <el-table-column prop="order_id" label="Order ID"></el-table-column> <el-table-column prop="ward_number" label="Ward Number"></el-table-column> </el-table> <el-dialog :visible.sync="qrDialogVisible"> <div id="qr-scanner-container" ref="scannerContainer"></div> <div slot="footer"> <el-button @click="qrDialogVisible = false">Cancel</el-button> </div> </el-dialog> </div> </div> {% endverbatim %} <script src="{% static 'js/vue.min.js' %}"></script> <script src="{% static 'js/axios.min.js' %}"></script> <script src="{% static 'js/qr-scanner.min.js' %}"></script> <script src="{% static 'js/qr-scanner-worker.min.js' %}"></script> <script> new Vue({ el: '#app2', data() { return { list: [], qrDialogVisible: false, selectedRow: null } }, mounted() { this.getemrList() }, methods: { getemrList() { // Obtain EMR list axios.post(ToDJ('emrList'), new URLSearchParams()).then(res => { if (res.data.code === 0) { console.log(res.data.data) this.list = res.data.data } else { this.NotifyFail(res.data.data) } }) }, showQRScanner(row) { this.selectedRow = row; this.qrDialogVisible … -
How to send response json from celery to my view Django
I want to use request_cache from 3rd party API and im looking for way to synch that every 5 minutes and if API is not responding or it got errors i want to use last json which i got from requests_cache I actually want to use celery for mb synch my request every 5 minutes and update that request but is this right way to do that? Or i just need to use expire_after in my view and i dont need to use celery Any solutions how can i do that? views.py def get_queryset(self): url = config('REPORT_PROJECT_BUDGET') session = requests_cache.CachedSession('project_budget_cache') response = session.get(url, auth=UNICA_AUTH) session.settings.expire_after = 300 # Im not sure if its right decision -
I can't see the buttons because of the image sizes in Django
I am trying to develop an application to display some food items in Django. Images overlay buttons when I try upload some of them. I tried solutions but couldn't fix the problem. I will be happy if you help me. Have a nice day. {% extends 'foodApp/base.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% block body %} {% for item in item_list %} <div class="row m-5"> <div class="col-md-3 offset-md-2"> <img class="card" height="auto" src="{{ item.item_image }}"/> </div> <div class="col-md-2"> <a href="{% url 'foodApp:detail' item.id %}" class="btn btn-success">Details</a> </div> </div> <div class="row"> <div class="offset-md-2 col-md-8"> <hr> </div> </div> {% endfor %} {% endblock %} this is the old code <ul> <li> <a href=""> {{ item.id }} -- {{ item.item_name }}</a> </li> </ul> </body> </html> It is my index source code. enter image description here -
"Request failed with status code 500" when I try opening my products page
This is my first time using redux and django. I click the link to one of my products that takes me to the products page, but I get a 500 error instead. My django server is running in the back and I know it's working because I get an error response in my terminal. I suspect my issue might be my views.py but I'm not sure since I'm not very familiar with django yet. ProductPage.js import React, { useState, useEffect } from "react"; import { Link, useParams } from "react-router-dom"; import { Row, Col, Image, ListGroup, Card, Button } from "react-bootstrap"; import Rating from "../components/Rating"; import Loading from "../components/Loading"; import ErrorMessage from "../components/Error"; import { useDispatch, useSelector } from "react-redux"; import { listProductsDetails } from "../actions/productActions"; function ProductPage() { const { id } = useParams(); const dispatch = useDispatch(); const productDetails = useSelector((state) => state.productDetails); const { loading, error, product } = productDetails; useEffect(() => { dispatch(listProductsDetails(id)); }, [id]); return ( <div> <Link to="/" className="btn btn-light my-3"> Go Back </Link> {loading ? ( <Loading /> ) : error ? ( <ErrorMessage variant="danger">{error}</ErrorMessage> ) : ( <Row> <Col md={6}> <Image src={product.image} alt={product.name} fluid /> </Col> <Col md={3}> <ListGroup variant="flush"> <ListGroup.Item> <h3>{product.name}</h3> … -
Need to set up an event listener in django
I need to listen to an external API from another application.Both applications have same number of users.so change in any app will need to be update on another app. SO planning to setup an event listener to communicate b/w applications. Appreciate any help to setup this in DJango. -
I need to make VoIP calls with python django
I have Auto Dialer web page's frontend now I need to make the backend, that should send VoIP calls to given files phone numbers and when answered play given audio file. I have no idea how to do that:( please can someone help -
Is it possible to create a admin page using curd operation in django?
I want to create a page where i can create update read delete (CURD) a user data like email password username role (Admin/normal user) etc., and all this update will automatically authenticate automatically. Basically i want to create a custom admin system. I have tried the curd operation from the tutorials but im unable to understand how do the connection between my table and djano user auth table. -
Overriding method python class of a pip module to update its behavior globally
Using OOP I want to do something like from django.contrib import admin class NavigateFormAdmin(admin.ModelAdmin): def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): context['next_record_id'] = custom_function_to_calculate(context['obj'].id) res = super().render_change_form(request, context, add, change, form_url) return res And expect that whenever render_change_form of admin.ModelAdmin is called, it should first my overridden method (above) which then should call the original (parent) method. but it makes no difference, because my overridden method never gets called rather on any call to render_change_form the method from original class admin.ModelAdmin is called. Using undesired monkey patching I am able to achieve what I need by adding following code to any of my py file that is read by interpreter at the start of my project/service execution from django.contrib import admin from django.template.response import TemplateResponse # and also all the other imports used in original medthod class NavigateFormAdmin(admin.ModelAdmin): def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): opts = self.model._meta app_label = opts.app_label preserved_filters = self.get_preserved_filters(request) # and all the code of existing function has to be repeated here context['next_record_id'] = custom_function_to_calculate(context['obj'].id) res = TemplateResponse(request, form_template, context) return res admin.ModelAdmin.render_change_form = NavigateFormAdmin.render_change_form Now on every call to admin.ModelAdmin.render_change_form off-course NavigateFormAdmin.render_change_form is executed But I need to use super() like (the … -
ERROR: Could not find a version that satisfies the requirement tappythonsdk from versions: noneERROR: No matching distribution found for tappythonsdk
can someone with more experience help me? ERROR: Could not find a version that satisfies the requirement noon-payment-gateway (from versions: none) ERROR: No matching distribution found for noon-payment-gateway im tried to use this command pip install tap-python-sdk This Package for Tap payment getaway for saudi arabia "SAR" Package for payment to build saudi arabia payment getaway with django -
Django - runserver command doesnt do anything
I activate the venv and when I try to run the python manage.py runserver command on VScode powershell it doesnt do anything, no errors, nothing, I enter the localhost to see if the server was activated with no notice but it doesnt appear. Note that the project was first made by a friend that uses Linux and I imported the project using Github on Windows, im thinking that there may be problems because of that? I tried running it on cmd and i couldnt run the activate command this time, apparently I need to use power shell to run linux like commands? Sorry Im a student and im not very knowledgeable on Linux. -
how to Django Admin Customization with self made design
Instead of using default Django Admin panel, I create My Own Admin Dashboard With HTML and CSS and other , So I want to apply default Django Admin panel Features like add, update, delete, filters, user Creation features to my Customize Admin Dashboard. Django default Admin dashboard Customize with my own design. -
Is there any auxiliary tool or quick way to upgrade django 3.0.5 to django 4.x?
My django is built from 3.0.5, and now the system is very large. If I want to upgrade to Django 4.x, I will encounter many problems. Are there many people who have encountered such troubles like me, so I wonder if anyone has a solution? -
Not receiving POST request
can someone help me? I am trying to when button is clicked and user clicks on proceed, send a POST request to the server in which it would switch user status from active to archive and vice versa. However, I am not receiving post request even though I have updated the form method to post and button to submit. I cannot find the root cause of the problem. Help is much appreciated! Thanks! Do let me know if there are any other codes that I should provide! HTML & Javascript: // Get the buttons var archiveBtn = document.getElementById("archive-btn"); var unarchiveBtn = document.getElementById("unarchive-btn"); var deleteBtn = document.getElementById("delete-btn"); // Get the modal forms var archiveForm = document.getElementById("archive-form"); var unarchiveForm = document.getElementById("unarchive-form"); var deleteForm = document.getElementById("delete-form"); // Add event listeners to the buttons archiveBtn.addEventListener("click", function() { archiveForm.submit(); }); unarchiveBtn.addEventListener("click", function() { unarchiveForm.submit(); }); deleteBtn.addEventListener("click", function() { deleteForm.submit(); }); <div id="archive-modal" class="modal fade " tabindex="-1" role="dialog" aria-modal="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-body p-4"> <div class="text-center"> <i class="dripicons-warning h1 text-warning"></i> <h4 class="mt-2">Are You Sure?</h4> <p class="mt-3">Archive User</p> <button type="button" class="btn btn-danger my-2" data-bs-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-primary my-2" data-bs-dismiss="modal">Proceed</button> <form method="post" action="{% url 'app:users' %}" id="archive-form" style="display:none;"> {% csrf_token %} <input type="hidden" name="user_id" … -
What is the best way to increment these likes and checks model attributes in a callback function using an if-elif-else statement?
I dont want to create two callback functions. I want this callback to execute in a conditional way using an if-elif-else statement. Firstly, will the code work well as it is? So if not, what is the best way to put the house.likes and house.checks in an if-else or if-elif-else statement? def callback(ch, method, properties, body): print('Received in config') id = json.loads(body) print(id) house = House.objects.get(id=id) house.likes = house.likes + 1 house.save() print('House likes increased!') house.checks = house.checks + 1 house.save() print('House checks increased!') I am yet to try refactoring it...still studying the code block. I don't want to break things. -
Strange errors using factory_boy and DjangoModelFactory
I've created several factories including a user factory that looks like so class UserFactory(factory.django.DjangoModelFactory): class Meta: model = models.User django_get_or_create = ('phonenumber',) uuid = factory.Faker('uuid4') email = factory.Faker('email') phonenumber = factory.Sequence(generate_phone_number) I'm using the django unit test TestCase model like so class ApiV1TestCase(TestCase): def setUp(self): self.user = UserFactory.create() and getting the following error: *** django.db.utils.IntegrityError: duplicate key value violates unique constraint "accounts_user_pkey" DETAIL: Key (id)=(1) already exists. when I run it several times I get a continual error with what looks like a correctly autoincremented ID field, ie. Key (id)=(2) already exists. ... Key (id)=(3) already exists. on each subsequent create() call. If I check the test database, I see that User.objects.all() is empty in all of these cases. Alternatively I'm able to successfully run UserFactory.build() u.save() however this isn't great for obvious reasons (ie. I want to override an auto_now datetime field in some tests) I've also noticed some strange behavior, if I check transaction.get_connection().in_atomic_block from django.db.transaction I get True which seems to indicate somehow that I'm in an atomic block? I'm not sure if this is normal behavior. -
How to unit testing for json file is loaded in django views.py
I want to unit testing for json file is opened in views.py in django def get_json_data(): json_data = json.load(open(JSON_DIRECTORY+'my.json')) return json_data Please help me how to unit testing for json file is loaded or not def test_read_file_data(self): def read_file_data(filename, path): os.chdir(path) with open(filename, encoding="utf8") as data_file: json_data = json.load(data_file) return json_data sample_json = { } sample_json = json.dumps(sample_json, ensure_ascii=False) path = my file path filename = real file self.assertEqual(read_file_data(filename, path), sample_json) In json there is null as well so I do not know how to deal with the null -
Ajax filters displays all data but does not filter. DJANGO AJAX
i'm using ajax filtering to filter my products by color, brand, size. The data filtering successfully but it shows everything. I'm hoping for your help and thank you for your attention Trying to filter products... product-filter.js:20 {data: '\n\n \n <div class="col-md-4 mb-0">\n … </div>\n </div>\n </div>\n \n'}data: "\n\n \n <div class=\"col-md-4 mb-0\">\n[[Prototype]]: Object product-filter.js:21 Data filtered successfully ajax $(document).ready(function(){ $(".filter-checkbox").on('click', function(){ let filter_object = {}; $(".filter-checkbox").each(function(index,ele){ let filter_value = $(this). val(); let filter_key=$(this). data('filter'); filter_object[filter_key]=Array.from(document.querySelectorAll('input[data-filter='+filter_key+']:checked')).map(function(element){ return element.value; }); }); $.ajax({ url:'/filter_products', data:filter_object, dataType:'json', beforeSend:function(){ console.log('Trying to filter products...'); }, success:function(response){ console.log(response); console.log('Data filtered successfully'); $("filteredProducts").html(response.data) } }); }); }); views.py def filter_products(request): color = request.GET.getlist('color[]') brand = request.GET.getlist('brand[]') size = request.GET.getlist('size[]') products = Product.objects.all().order_by('-id').distinct() if len(color)>0: products=products.filter(color__id__in=color).distinct() if len(brand)>0: products=products.filter(brand__id__in=brand).distinct() if len(size)>0: products=products.filter(size__id__in=size).distinct() t = render_to_string('ajax/product-list.html',{'products':products}) return JsonResponse({'data':t}) def search(request): data1 = wishData(request) wishItems = data1['wishItems'] data = cartData(request) q = request.GET['q'] cartItems = data['cartItems'] products = Product.objects.filter(name__icontains=q).order_by('id') context = {'products': products, 'cartItems': cartItems,'wishItems': wishItems} return render(request, 'store/store.html', context) def product_view(request, id): product = Product.objects.filter(id=id).first() data = cartData(request) cartItems = data['cartItems'] data1 = wishData(request) wishItems = data1['wishItems'] context = {'product':product, 'cartItems':cartItems, 'wishItems':wishItems} return render(request, 'store/product_view.html', context) def store(request): data1 = wishData(request) wishItems = data1['wishItems'] data = cartData(request) cartItems = data['cartItems'] … -
Why does my dependent dropdown form act up?
I am attempting to implement a dependent dropdown form for my project. I want the makes dropdown to be dependent of the year of the vehicle. The models dropdown entries should be dependent on the year and make dropdown entries selected. Finally, the repairs dropdown should be dependent on the year, make, and model selected. However, this is not the case. In my django database, I have two entries titled "Chevrolet" that are connected to years 1980 and 1981 via ForeignKey. Both of these entries are connected to an entry titled "Camaro". Another entry I have stored in my backend database has 1981 as the year, "Ford" as the make (connected to 1981 via ForeignKey), and "LTD Crown Victoria" and "F-150" as models. While the year and makes appear as they should, the other entries do not. I can only get the appropriate models to appear in the dropdown box after I select 1981 as the year and "Ford" as the model. Afterwards, I am able to see the models connected with the 1981 entry for "Chevrolet". Code from my Home.html file {% load static %} <!doctype html> <html lang="en"> <link rel="stylesheet" href="{% static 'css/edits.css' %}"> <head> <meta charset="UTF-8"> <meta … -
Completing and order using choice fields
I am trying to make it so when an order processed and payment is made, the payment status is changed to complete. At the moment my orders stay on pending consistently. What should be happening is that the order is completed the page is redirect to home page, cart is emptied and payment status changes to 'Complete' Models: class Order(models.Model): PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F' PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed') ] customer = models.ForeignKey( Customer, on_delete=models.PROTECT, null=True, blank=True) order_id = models.IntegerField(null=True) order_date = models.DateTimeField(auto_now_add=True) payment_status = models.CharField( max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING ) def __str__(self): return str(self.id) @property def get_cart_items(self): order_items = self.orderitem_set.all() total = sum([item.quantity for item in order_items]) return total @property def get_cart_total(self): order_items = self.orderitem_set.all() total = sum([item.get_total for item in order_items]) return total views: if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, payment_status='P') #TODO: add float field? total = data['form']['total'] order.order_id = order_id if total == order.get_cart_total: order.payment_status = 'C' order.save() JS var total = '{{order.get_cart_total}}' var form = document.getElementById('form') form.addEventListener('submit', function(e){ e.preventDefault() console.log('Form Submitted..') document.getElementById('form-button').classList.add('hidden'); document.getElementById('payment-info').classList.remove('hidden'); }) document.getElementById('make-payment').addEventListener('click', function(e){ submitFormData() }) function submitFormData(){ console.log('Payment button clicked') var userFormData = { 'first_name':null, 'last_name':null, 'email':null, 'total':total, } var url = …