Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting error on migrating raise TypeError("'Collection' object is not callable. If you meant to " TypeError: 'Collection' object is not callable
I am using djongo to connect my rest_framework API with MongoDB. I have deleted the 0001_initial.py file and try to push the migrations using python manage.py makemigrations and python manage.py migrate but I am getting these errors while doing this. my settings.py file DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'TMS', } } (env) D:\inductionplan\django-api\backend>python manage.py migrate Operations to perform: Apply all migrations: admin, api, auth, authtoken, contenttypes, sessions, token_blacklist Running migrations: This version of djongo does not support "NULL, NOT NULL column validation check" fully. Visit https://nesdis.github.io/djongo/support/ Applying contenttypes.0001_initial...This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying auth.0001_initial...This version of djongo does not support "schema validation using KEY" fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "schema validation using REFERENCES" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name...This version of djongo does not support "COLUMN DROP NOT NULL " fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "DROP CASCADE" fully. Visit https://nesdis.github.io/djongo/support/ Traceback (most recent call last): File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 894, in _alter query.execute() File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 533, in _drop_column self.db[self.left_table].update( … -
Insert data into models which has a foreign key in Django
I want to perform the below query in Django models where image and caption is the field of posts model and user is the foreign key of posts model : insert into posts values('" + user + "','" + image + "','" + caption + "') Here are my models: #posts model class Posts(models.Model): user=ForeignKey(User, on_delete=models.CASCADE) image=ProcessedImageField(upload_to="/images",help_text="Post", verbose_name="Post", processors=[ResizeToFill(400, 400)], format='JPEG', options={'quality': 80}) caption=models.CharField(max_length=40,null=True,default=" ",blank=True) def __str__(self): return self.user.username #user model the default user model #views def UploadPost(request): if 'user' in request.session: if request.method=='POST': post_form=UploadPostForm(request.POST, request.FILES,instance=request.user) if post_form.is_valid(): post_form.save() messages.success(request,"post uploaded") else: return error else: post_form=UploadPostForm(instance=request.user) return render(request, 'users/upload_post.html', context={'post_form': post_form}) else: return redirect('login') #html {% extends "users/base.html" %} {% load static %} {% block content %} <div class="container text-center"> {% if messages%} {% for msg in messages%} {{msg}} {%endfor%} {%endif%} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{post_form.as_p}} <button class="btn btn-outline-dark" type="submit">Upload</button> </form> <a href="{% url 'logout'%}">logout</a> </div> {% endblock content %} when I click on the upload button, it shows the success message but the post isn't uploaded -
Django (DRF) - get_queryset - Trying to return "images" with model "Product" as an extra field
I'm trying to make a queryset which returns all Products. Every Product has one or more ProductImages and I want to add them as an extra field "images" for every product. So the response I'm after is like [ { id: 1, name: "prod1", images: images } ] I've tried the following implementations: Models class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() price = models.FloatField() class ProductImage(models.Model): name = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.CASCADE) My idea implemented in the simplest way class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def get_queryset(self): queryset = Product.objects.all() product_list = [] # iterate over all products for product in queryset: images = ProductImage.objects.filter(product=q.id) product['images'] = images product_list.append(product) return product_list gives error "TypeError: 'Product' object does not support item assignment" New idea, make a new dict and add elements of product and add "images" as an extra field. class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def get_queryset(self): queryset = Product.objects.all() product_list = [] # iterate over all products for q in queryset: images = ProductImage.objects.filter(product=q.id) product = {"id": q.id, "name": q.name, "description": q.description, "price": q.price, "images": images} product_list.append(product) return product_list gives error Internal Server Error: /api/product/ Traceback (most recent call last): File "C:\Users\Simon\.virtualenvs\django_backend-ZmgaAA1F\lib\site-packages\django\core\handlers\exception.py", line … -
UNIQUE constraint failed: account_customuser.username
I have a problem with user's signup. I use Django. When I register the first user everything is fine and the user appears in the admin panel. The problem occurs when I want to register the second user. After submiting the signup form, this error shows up: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: account_customuser.username So it looks like the user will not be saved because the username (email) is not unique, but the email of the second user is different from the first one. Only superuser and first registered user appear at the admin panel. models.py from django.db import models from django.contrib.auth.models import AbstractUser from orders.models import Order class CustomUser(AbstractUser): email = models.EmailField(unique=True, max_length=255, default='') zip_code = models.CharField(max_length=6) address = models.CharField(max_length=255) street = models.CharField(max_length=255) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) email_confirmed = models.BooleanField(default=False) orders = models.ForeignKey( Order, related_name='orders', on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email views.py from django.shortcuts import render, redirect from .forms import CreateUserForm def signup(request): form = CreateUserForm() if request.method … -
Root domain showing nginx default welcome page while subdomain (www) is ok
I am using django + nginx and so far I encounter this issue where if I go to www.stochie.com or the IP address it work fine while if i type in stochie.com it has some issue as in showing the nginx welcome or default page. here is my nginx config file: server { listen 80; server_name www.stochie.com stochie.com "" 18.139.57.168 ; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/stochie; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } while in the django settings.py: ALLOWED_HOSTS = ['www.stochie.com', 'stochie.com', '18.139.57.168'] and in the google domain: Hostname Type TTL Data stochie.com A 1 hour 18.139.57.168 www.stochie.com CNAME 1 hour stochie.com. After checking around, figure out it might be due to nginx using the default config instead of the stochie config but when it is not possible to modify and remove the default config due to permission issues. So currently not sure how to go about this :( -
how to create list history django
sweetest programmer, I am still a beginner And I made a warehouse program with django There is something standing in front of me, but I want to create a page that answers the history of all the arguments that have been added or disposed of. For example, if I add the same girl like this once, it will only give me the total. I want to make a page that answers item details. Added how many times in what days? I want to create a page like the simple history admin, but it remains in my form so that I can control it. Anyone can help me with this. Thank you for it -
no such function: to_tsvector - Django
I'm using Django and PostgreSQL. I have a website where I want to be able to search for books based on both author and its title. I'm using SearchVector to search in both of these fields together. Here's my view: def search(request): query = request.GET.get("query") searched = Book.objects.annotate(search=SearchVector('title', 'author'),).filter(search=query) return render(request, "main/search.html", { "query": query, "searched": searched, }) Here's my template: {% extends "main/base.html" %} {% load custom_filters %} {% block content %} <h1>You searched for {{ query }}</h1> {% for book in searched %} <div class="reading_box"> <h3>{{ book.title }}</h3> <p>{{ book.author }}</p> </div> {% endfor %} {% endblock %} Django gives this weird error about a function I've never even heard of: Internal Server Error: /main/search/ Traceback (most recent call last): File "/opt/homebrew/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/opt/homebrew/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such function: to_tsvector The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/homebrew/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/homebrew/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/adithraghav/Documents/Work/centel/books/main/views.py", line 369, in search return render(request, "main/search.html", { File "/opt/homebrew/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render content = … -
how wrapper function works with same name within different functions in python?
i have two wrap function with same name within two different functions (in a single .py file) def related_to_restaurant(function): def wrap(request, *args, **kwargs): user = AuthUserExtension.objects.filter(Q(user_id=request.user.id)&Q(is_restaurant=True)).exists() data = get_auth_user_extentension(request.user.pk) if data: data = data[0] user_admin = data.is_team_member else: user_admin = False if user or (user_admin and request.user.is_active) or request.user.is_superuser: return function(request, *args, **kwargs) else: # raise PermissionDenied return redirect('logout_store_user') #return function(request, *args, **kwargs) return wrap def user_has_restaurant(function): def wrap(request, *args, **kwargs): restaurant_id = kwargs["restaurant_id"] print({"restaurant_id": restaurant_id}) if int(restaurant_id) != -1: restaurant = RestaurantUser.objects.filter(Q(user_id=request.user.id)&Q(restaurant_id=restaurant_id)).exists() else: restaurant = True data = get_auth_user_extentension(request.user.pk) if data: data = data[0] user_admin = data.is_team_member else: user_admin = False if restaurant or request.user.is_superuser or (user_admin and request.user.is_active): return function(request, *args, **kwargs) else: # raise PermissionDenied return redirect('list_restaurant') return wrap I'm using both as a decorator for different functions So when i call @related_to_restaurant decorator it calls the wrap function of both the functions related_to_restaurant and user_has_restaurant. is this how decorator works or I'm doing something wrong in it. -
Django how to add query results foreign key model to queryset
How can I get the Author model objects into a queryset through the foreign key of B model? I would like to use the Author objects in my template. #Models.py class Book(models.Model): name = models.CharField(max_length=5) class Author(models.Model): # lots of fields class B(models.Model): author = models.ForeignKey(Author) book = models.ForeignKey(Book) selected_book = "ABC" book = Book.objects.get(name=selected_book) original_queryset = B.objects.filter(name=book) for i in original_queryset: print(i.author) # returns what i want queryset = # get all i.author objects somehow return render(request,"template.html", {"queryset": queryset} -
How to send django url with parameters to ajax request?
Currently, I am sending url to the ajax as : $('.togglebtn').on("click",function(){ console.log("Hello") $.ajax({ type: 'GET', url: "http://localhost:8000/toggle/2945016571198", contentType: 'application/json', success: function (data) { appendData(data); function appendData(data) { var mainContainer = document.getElementById("switch_{{forloop.counter}}"); for (var i = 0; i < data.length; i++) { var div = document.createElement("div"); div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ; mainContainer.appendChild(div); } } } }); Currently, I am sending request into a static url. Can we use {% url toggle i.id %} to set the url dynamically in the ajax request? Does this ajax function repeats at all or not? -
Issue executing cron job using django_crontab
I have followed the instructions to use Django-crontab package to execute my cronjobs.The cronjobs gets executed perfectly if I run the command "python manage.py crontab run ".However when I run the server , I get an error Traceback (most recent call last): File "/Users/Documents/GitHub/python_test_env/lib/python3.8/site-packages/django/core/management/init.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'crontab' -
How to use variables as name of fields in order to update objects dynamically in Django
there are three fields in the model below in a Django app, just for example. class MyModel(models.Model): field1 = models.IntegerField(default=0, blank=False,null=False) field2 = models.IntegerField(default=0, blank=False,null=False) field3 = models.IntegerField(default=0, blank=False,null=False) In order to update multiple fields, I want to use a variable "target_field" instead of using each name of fields. for i in (1,3): target_field = "field{0}".format(i) sample_object = get_object_or_404(MyModel, id=sample_d) sample_object.target_field = "sample_value" # this couldn't work. sample_object.save() In the code described above, "target_field" is not recognized as a name of fields. -
IsOwnerOrReadOnly permission
Im trying to do crud api with IsOwnerOrReadOnly permission but other users can still delete posts from the others. Could you please have a look. I have no clue what goes wrong // permissions.py from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self,request,view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user.userprofile // views.py class PostDetail(APIView): permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, ] def get_obj(self, pk): try: return Post.objects.get(id=pk) except Post.DoesNotExist: raise Http404 def get(self, request, pk, format=None): post = self.get_obj(pk) serializer = PostSerializer(post) return Response(serializer.data) def put(self, request, pk, format=None): post = self.get_obj(pk) serializer = PostSerializer(post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): post = self.get_obj(pk) post.delete() return Response(status=status.HTTP_204_NO_CONTENT) // users.models.py class Profile(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True) intro = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_image = models.ImageField(default=None, upload_to='profile/', blank=True, null=True) github = models.CharField(max_length=200, blank=True, null=True) linkedin = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.user.username) -
Django social auth login to google redirects to sign up page
Created a link to go to the Google sign in <a class="nav-link pl-3" data-target="#navigationbar" href="https://<my-site>/accounts/google/login/?process=login">Login</a> It redirects to /accounts/social/signup/ instead of showing up the Google sign in page. enter image description here The very same code works perfectly fine on my local machine and directly goes to google sign in page enter image description here -
SHow django-debug-toolbar to specific users
I have seen this question over the issue of DjDT. However when I implement it gives an error. 'WSGIRequest' object has no attribute 'user' This is my code def show_toolbar(request): return not request.is_ajax() and request.user and request.user.username == 'ptar' DEBUG_TOOLBAR_CONFIG = {'SHOW_TOOLBAR_CALLBACK': 'libert.settings.show_toolbar',} -
Compare field in the table and calculated field in django-orm
I calculated one variable using the annotate and now i want to compare it with the existing field. So how can I do that? -
How we will count the User?
class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile_number = models.IntegerField() cnic = models.CharField(max_length=13) blood_group = models.CharField(max_length=10) last_donation = models.DateTimeField(auto_now_add=True) class Donation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'donation') donation_count = models.IntegerField(default= 1) First time user will come and donate blood Ok but now the condition is that existing user can donate Blood after 3 months. Now I have to check that which user donate blood how many times How I can Count the user I searched too much but didn't find anything related to this Can anyone help me I have Two models. Thanks in advance -
Spanning multi-valued relationship
Spanning multi-valued relationships When spanning a ManyToManyField or a reverse ForeignKey (such as from Blog to Entry), filtering on multiple attributes raises the question of whether to require each attribute to coincide in the same related object. We might seek blogs that have an entry from 2008 with “Lennon” in its headline, or we might seek blogs that merely have any entry from 2008 as well as some newer or older entry with “Lennon” in its headline. To select all blogs containing at least one entry from 2008 having “Lennon” in its headline (the same entry satisfying both conditions), we would write: Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008) Otherwise, to perform a more permissive query selecting any blogs with merely some entry with “Lennon” in its headline and some entry from 2008, we would write: Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008) Suppose there is only one blog that has both entries containing “Lennon” and entries from 2008, but that none of the entries from 2008 contained “Lennon”. The first query would not return any blogs, but the second query would return that one blog. (This is because the entries selected by the second filter may or may not be the same as the entries in the first filter. We … -
How to provide seekable/scrubbable audio to frontend using Django
I'm trying to provide audio to the HTML Django template, originally I tried like this: <audio id="audio" src="{{audio_path}}" controls></audio> This was sufficient to get audio playing on the website with pause/play, speed up/down, volume up/down but the user was not able to move the progress bar at all, it either froze, or returned to the starting position. I did lots of searching and found many things that claimed to enable seeking/scrubbing, but none of them have worked. Currently my code is as follows, first the audio API view: class AudioFetchView(View): def get(self, request, audio_id, *args, **kwargs): audio_file = UploadAudio.objects.get(pk=audio_id) response = StreamingHttpResponse(content_type='audio/mpeg') response['Content-Disposition'] = 'attachment; filename=%s' % audio_file.path response['Accept-Ranges'] = 'bytes' response['X-Sendfile'] = audio_file.path return response audio_fetch = AudioFetchView.as_view() Then the HTML: <audio id="audio" crossOrigin="anonymous" preload="auto" src="{{audio_fetch_url}}"></audio> Now the audio is not able to be played at all, the error message is: "Uncaught (in promise) DOMException: The element has no supported sources." Does anyone know how to correctly provide an .mp3 file to the frontend in a way that allows scrubbing/seeking? -
How to register a device on FCMDevice of fcm-django?
I'm a beginner at Django. Referring to this link, I installed fcm-django and finished setting. fcm-django doc Install fcm-djagno. pip install fcm-django Setting fcm-django on settings.py. import firebase_admin from firebase_admin import credentials cred_path = os.path.join(BASE_DIR, "serviceAccountKey.json") cred = credentials.Certificate(cred_path) firebase_admin.initialize_app(cred) ... INSTALLED_APPS = [ ... 'fcm_django', ] ... FCM_DJANGO_SETTINGS = { # default: _('FCM Django') "APP_VERBOSE_NAME": "django_fcm", # Your firebase API KEY "FCM_SERVER_KEY": "AAAAsM1f8bU:APA91bELsdJ8WaSy...", # true if you want to have only one active device per registered user at a time # default: False "ONE_DEVICE_PER_USER": False, # devices to which notifications cannot be sent, # are deleted upon receiving error response from FCM # default: False "DELETE_INACTIVE_DEVICES": True, } And, when I post notice, if push is active, I try to send push notifications to all devices. from firebase_admin.messaging import Message, Notification from fcm_django.models import FCMDevice class noticeCreateView(View): def post(self, request, *args, **kwargs): title = request.POST.get('title') content = request.POST.get('content') push = request.POST.get('push') if push: message = Message( notification=Notification( title=title, body=sentence, ), ) try: devices = FCMDevice.objects.all() devices.send_message(message) except Exception as e: print('Push notification failed.', e) return HttpResponseRedirect(reverse('notice_list')) What I am curious about is whether data is automatically added in the FCMDevice model when the user installs this app. If I … -
Django - advanced search
I need to apply advanced search filters to my database to search effectively. I use Django and PostgreSQL. Some things in my list of "advanced search filters": In default behaviour, it's going to ignore stop words, such as "a", "the", and "is" Searching for exact phrases by enclosing text in "" Since this is a website where books are uploaded, books written by a specific author Books for a certain age group Books in a certain genre If I get all of these from within regular expressions, how am I supposed to search for them? I think I can think of how to do all of these, but I just wanted to know of a way to do it without using a list of stop words and try not to consider them or something like that. Is there any feature in Django that can help me to these effectively and with relatively less effort? -
Sum of field in a consecutive period based on a condition
I did this without complicated query and with Python. But I'm looking for a way to do this with Django ORM. I have a table as follows: user date point Mary 2022/01/04 13 John 2022/01/04 10 Mary 2022/01/03 0 John 2022/01/03 5 Mary 2022/01/01 1 John 2022/01/01 1 Mary 2021/12/31 5 I want to calculate the Sum of points from now() to the date when the point value is greater than one. Desired Output: user sum Mary 14 13+1 John 10 10 -
Not able to post data in database through django model forms
I have been trying to create a contact us form and not been able to post data to the database . I have tried the print function and that gives all the inputs. I have tried almost everything around but not able to solve this. After clicking submit, the page just refreshes but nothing is added in the database. Please help!!! Models.Py from django.db import models from datetime import datetime # Create your models here. class Contact(models.Model): name = models.CharField(max_length=200) email = models.EmailField(max_length=255) subject = models.CharField(max_length=200) message = models.TextField(max_length=1000) contact_date = models.DateTimeField(auto_now=True) def __str__(self): return self.name Forms.py from django import forms from .models import Contact class ContactUsForm(forms.ModelForm): class Meta: model = Contact fields = ['name','email','subject','message'] widgets= { 'name': forms.TextInput(attrs={'class': 'form-control form-control-light',}), 'email': forms.EmailInput(attrs={'class': 'form-control form-control-light',}), 'subject': forms.TextInput(attrs={'class': 'form-control form-control-light',}), 'message': forms.Textarea(attrs={'class': 'form-control form-control-light',}), } Views.py from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponse, HttpResponseRedirect from .forms import ContactUsForm from .models import Contact # Create your views here. def index(request): if request.method == 'POST': form = ContactUsForm(request.POST) if form.is_valid(): form.save messages.success(request,"Plan created successfully.") return redirect(request.path) return render(request, 'pages/index.html',{'form':form}) else: form = ContactUsForm() return render(request, 'pages/index.html', {"form":form}) HTML <div class="col-md-8"> <form action="." method="POST"> {% csrf_token %} <div … -
wagtail upload file - InMemoryUploadedFile
I'm using wagtail form to save form data but when I upload file I get message error : Object of type 'InMemoryUploadedFile' is not JSON serializable the def of save I'm using is def serve(self, request, *args, **kwargs): if request.method == 'POST': recaptcha_response = google_captcha_validate(request) form = self.get_form(request.POST, request.FILES, page=self, user=request.user) if form.is_valid() and recaptcha_response.get('status'): if request.FILES['uploadcv']: myfile = request.FILES['uploadfile'] fs = FileSystemStorage(location='media/documents') filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) print(form) form_submission = self.process_form_submission(form) return JsonResponse({'success': True}) -
Multi Algoritms Precentage
I am making heart-disease-system. My question is how to improve my code, and show not only 0 - for none-risk and 1 - for having heart disease. Here is my view.py if form.is_valid(): features = [[ form.cleaned_data['age'], form.cleaned_data['sex'], form.cleaned_data['cp'], form.cleaned_data['resting_bp'], form.cleaned_data['serum_cholesterol'], form.cleaned_data['fasting_blood_sugar'], form.cleaned_data['resting_ecg'], form.cleaned_data['max_heart_rate'], form.cleaned_data['exercise_induced_angina'], form.cleaned_data['st_depression'], form.cleaned_data['st_slope'], form.cleaned_data['number_of_vessels'], form.cleaned_data['thallium_scan_results']]] standard_scalar = GetStandardScalarForHeart() features = standard_scalar.transform(features) SVCClassifier,LogisticRegressionClassifier,NaiveBayesClassifier,DecisionTreeClassifier=GetAllClassifiersForHeart() predictions = {'SVC': str(SVCClassifier.predict(features)[0]), 'LogisticRegression': str(LogisticRegressionClassifier.predict(features)[0]), 'NaiveBayes': str(NaiveBayesClassifier.predict(features)[0]), 'DecisionTree': str(DecisionTreeClassifier.predict(features)[0]), } pred = form.save(commit=False) l=[predictions['SVC'],predictions['LogisticRegression'],predictions['NaiveBayes'],predictions['DecisionTree']] count=l.count('1') result=False if count>=2: result=True pred.num=1 else: pred.num=0 pred.profile = profile pred.save() predicted = True colors={} if predictions['SVC']=='0': colors['SVC']="table-success" elif predictions['SVC']=='1': colors['SVC']="table-danger" if predictions['LogisticRegression']=='0': colors['LR']="table-success" else: colors['LR']="table-danger" if predictions['NaiveBayes']=='0': colors['NB']="table-success" else: colors['NB']="table-danger" if predictions['DecisionTree']=='0': colors['DT']="table-success" else: colors['DT']="table-danger" if predicted: return render(request, 'predict.html', {'form': form,'predicted': predicted,'user_id':u_id,'predictions':predictions,'result':result,'colors':colors}) else: form = Predict_Form() return render(request, 'predict.html', {'form': form,'predicted': predicted,'user_id':u_id,'predictions':predictions}) ipynb of all algorithms shows accuracy in precentage, but when i am making predict it shows 1 or 0, I need to show accuraccy like for example: Linear Regression: 75% (if more than 70% it is red, else green)