Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to mock and test a django view including external api call
I want to test a django view which includes a call to an external API. The API call is wrapped up by another package (jira). When the view is called a jira ticket is created for a Project (model). How would I properly test the view while preventing that the external API is called. The view looks like this: class RequestHelp(View): def get(self, context, pk=None, **response_kwargs): # get the project to create the ticket for project = Project.objects.get(id=pk) # initialize the jira client jira = JIRA( server=settings.JIRA_URL, basic_auth=(settings.JIRA_USERNAME, settings.JIRA_PASS), ) # create the ticket in jira new_issue = jira.create_issue( project=settings.JIRA_PROJECT, summary= project.title , description="Would you please be so nice and help me", reporter={"name": "My User"}, issuetype={"name": "An Issue"}, ) return HttpResponseRedirect("/") The test at the moment looks like this: class TestRequestHelp(TestCase): @classmethod def setUpTestData(cls): cls.std_user = User.objects.create_user( username="john", email="john@doe.de", password="secret", is_staff=False, is_superuser=True, ) def test_get_help_logged_in(self): self.client.login(username="john", password="secret") project, status = Project.objects.get_or_create(title="Test") response = self.client.get(f"/project/help/{project.pk}", follow=True) self.assertEqual(200, response.status_code) A "normal" test of the view works but always creates a ticket which is not desirable. Any help with this would be appreciated. -
How can I autofill a field in my django form in class based view?
I create an opportunity for users to comment on the book. I have a list of books, where all the books in the database are placed, and also a detail book for each book. I created a form for the possibility of commenting in detail book, where I pass various fields, but some I want to be autofilled not by the users themselves, such as the title of the book and the author. I managed to do it with the author, but the title of the book does not work. I would be grateful if you can help with this. models.py import uuid from django.db import models from django.db.models.enums import TextChoices from django.urls import reverse from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User class Genre(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) image = models.ImageField( upload_to="photos", default=None, blank=True, null=True) author = models.ForeignKey("Author", on_delete=models.SET_NULL, null=True) summary = models.TextField() isbn = models.CharField(max_length=10, unique=True, blank=True, null=True) genre = models.ManyToManyField("Genre", related_name="book_genre") publisher = models.ManyToManyField("Publisher") languages = models.ManyToManyField("Language") publication_date = models.DateTimeField(default=timezone.now) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse("book_detail", kwargs={"pk": self.pk}) class Meta: ordering = ["-created_date"] constraints = [ models.UniqueConstraint( fields=["title"], … -
"depth" in django rest framework: How to access values?
Here my requirement is to access values in the below structure which is get by using "depth" in the serializer. serializers.py class Meta: model = Course fields = ("is_favorite", "backgroundcolor", "instructor", "instructor_rating", "review_status", "id", "name", "description", "is_free", "image", "keyarea", "subject", "course_type", "beneficiary", "section", "datetime_created", "general_status", "review_status", "difficulty", "publish_date", "enrollment", "revenue", "category", "created_by", 'last_modified_by', 'course_rating', 'enrollment_type', 'expiry_data', "course_banner") depth = 3 The result structure: { "status": 200, "data": { "course": { "is_favorite": false, ..... ..... ..... "section": [ { "id": "5bf83a1c-e240-4907-9f71-e449644860b1", "deleted": null, "datetime_created": "11/29/2021 09:33 AM", "datetime_updated": "11/29/2021 09:33 AM", "name": "section1", "code": "22833", "description": "Description", "is_locked": true, "is_free": true, "modules": [ { "id": "0e82f2a5-6365-4206-b9e3-cd4e8e54f16c", "deleted": null, "datetime_created": "11/29/2021 09:32 AM", "datetime_updated": "11/29/2021 09:32 AM", "name": "module1", "description": "Description", "is_free": true, "videos": [ { "id": "8c7e70ec-703d-4c07-97ff-c69202451de8", "deleted": null, "datetime_created": "11/29/2021 08:05 AM", "datetime_updated": "11/29/2021 08:05 AM", "video_name": null, "description": null, "duration": "03:20:00", "create_date": "11/29/2021 08:05 AM", "video_type": "micro", "file_url": "https://vimeo.com/369126918", "general_status": "High", "review_status": "Draft", "created_by": null }, { "id": "ec4e3ce7-69e9-45d6-b00f-60f0012044bb", "deleted": null, "datetime_created": "11/29/2021 08:02 AM", "datetime_updated": "11/29/2021 08:02 AM", "video_name": null, "description": null, "duration": "00:01:40", "create_date": "11/29/2021 08:02 AM", "video_type": "micro", "file_url": "https://vimeo.com/369126918", "general_status": "High", "review_status": "Draft", "created_by": null } ] } ] } ], ...... ...... }, "success": … -
Python & Django - 'ModuleNotFoundError: No module named 'GoalCategoryTest'' when trying to import TestCase
So I have this TestCase file CategorySearchTest.py class CategorySearchTest(TestCase): @classmethod # Generates Test DB data to persist throughout all tests def setUpTestData(cls) -> None: cls.access_token = get_test_user_access_token() cls.user = get_or_create_test_user_in_DB() cls.goal_category_name_list = ['Health', 'Fitness', 'Art', 'Relationships', 'Artist'] I'm trying to import this in the init.py file in the same folder so I can run all the tests in this folder with the command python manage.py test <root>\test\CategoriesTest. my __init__.py file looks like this from GoalCategoryTest import * then here's my folder structure I'm getting the error from my __init__.py file which is ModuleNotFoundError: No module named 'GoalCategoryTest'. Why is this happening? I've tried from GoalCategoryTest import * and import GoalCategoryTest and both give the same error. -
how i can set the margin-left of the page to don't let the data spread along the width of the paper
Am newbie and am trying to use the library "reportlab" to generate the PDF, I want to fix the margin-left of the page but i did'nt know how i can do that : this is my code: c = canvas.Canvas(buf, bottomup=0) c.translate(inch,inch) textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 6) posts = Post.objects.all() lines = [] for post in posts: lines.append(post.title) lines.append(post.content) This is how it looks like : enter image description here But what i want is to fix the margin left -
Django - Show list datetime values in template
I have below code which outputs datetime values as shown below: available_hours = [hour for hour in hours_between if hour not in reserved_times] print(available_hours) [datetime.datetime(2021, 12, 8, 12, 0), datetime.datetime(2021, 12, 8, 13, 0), datetime.datetime(2021, 12, 8, 14, 0), datetime.datetime(2021, 12, 8, 16, 0), datetime.datetime(2021, 12, 8, 17, 0), datetime.datetime(2021, 12, 8, 18, 0), datetime.datetime(2021, 12, 8, 19, 0), datetime.datetime(2021, 12, 8, 20, 0), datetime.datetime(2021, 12, 8, 21, 0)] I render them in the template like: {{ available_hours }} and i got all above datetime values. How can i change the format so i can show them like Mon 12 2021, 21:00? Thank you -
django cascade delete on 2 foreign keys of the same table
I have a model A and model B. Model B has 2 foreign keys to model A as shown. There is a 1 to many relationship between Model A to B such that a dataset (A) can have multiple data elements(B). Model A: id (primary key) dataset_id dataset_version dataset_name Model B: id (primary key) dataelement_id dataelement_version dataelement_name fk_dataset_id fk_dataset_version My question is: How to cascade delete a row from Model A such that the deletion occurs on Model B using fk_dataset_id and fk_dataset_version together ? Currently, django runs 2 separate queries to delete data from Model B on columns fk_dataset_id and fk_dataset_version but I want the deletion query to use an AND condition for deletion for e.g. DELETE from model B where B.fk_dataset_id = 1 AND B.fk_dataset_version = 3 Iam using a django rest framework with ModelViewSet for both Model A and B -
How to skip validation in django model serializers?
Its a general question. I have a code where I have implemented the validation of the serializer. Now when I make a post request and validate the data by is_valid function, it should run the validate method. But when I make a patch request it validates the data again. I want to skip this part because in my validate function I am validating data using some fields which are sent by the client during the post request but not during the patch request. I am not sure how to deal with this. Can someone help me with this ? -
Django ORM using external database to unmanaged model in view says relation does not exist
I have two Postgres database connections and when using another than default ORM calls fail on views, but not raw. I am using docker and containers are connected and using Django's own runserver command. Using ORM in django command or django shell works fine, but not in a view. As a side note, both databases are actually Django-projects, but main project is reading some data directly from another project's database using own unmanaged model. Python: 3.9.7 Django: 3.2.10 Postgres: 13.3 (main project), 12.2 (side project) # settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'pguser', 'PASSWORD': 'pguser', 'NAME': 'mainproject', 'HOST': 'project-db', # docker container 'PORT': '5432', }, 'external': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'pguser', 'PASSWORD': 'pguser', 'NAME': 'sideproject', 'HOST': 'side-db', # docker container, attached to same network 'PORT': '5432', }, } # My unmanaged model class MyTestModel(models.Model): class Meta: # table does not exist in 'default', but it does exist in 'external' db_table = 'my_data_table' managed = False # my_data_table is very simple it has id field as integer # and primary key (works out of the box with django) # it has normal fields only like IntegerField or CharField # But even if this model is empty then … -
Update inheritance for multiple objects using django signal
I am implementing django signals to update a model which has been inherited by multiple other models. For instance, class A: name = models.CharField(max_length=199, blank=True, null=True) class B(A): id = models.PositiveIntegerField() class C(A): id = models.PositiveIntegerField() class D(A): id = models.PositiveIntegerField() If there are any changes upon save, I want to perform an operation. My implementation for Signal is as follows: @receiver(post_save, sender=B) def base_update(sender, instance, **kwargs): try: obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: # raise an error else: # do something At the moment, it works for B , but if I consider rest of the models I'd end up replicating the same function with different sender names. Is there a way to make a generic Signal that applies to all the models that inherits A ? -
How to Make a div fit A4 page
I have a django admin action function that display Transactions and loops through as many as queryset selected that will be rendered in html page, and converts the html to pdf. I want at the pdf that each transaction object fit in A4, not to have another transaction object in same page. here is code.. def report_pdf(self, request, queryset): if request.user.is_superuser: transaction = queryset else: transaction = queryset.filter(user=request.user) template_path = "single-pdf.html" context = {"transactions": transaction} template = get_template(template_path) html = template.render(context) file = open('test.pdf', "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.seek(0) pdf = file.read() file.close() return HttpResponse(pdf, 'application/pdf') and here is my html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Report</title> <style> </style> </head> {% for transaction in transactions %} <body> <div class="container"> {% if transaction.complete %} <table class="tg" > <thead> <tr> <th class="tg-4rlv">Report for Tenant</th> </tr> </thead> <tbody> <tr> <td class="tg-c6of" CHP Reference</span></td> <td class="tg-c6of">{{transaction.chp_reference}}</td> </tr> <tr> <td class="tg-c6of"> Rent Effective From(dd/mm/yyyy)</td> <td class="tg-c6of">{{transaction.rent_effective_date}}</td> </tr> <tr> <td class="tg-c6of"> CRA Fortnightly Rates valid for 6 months from</td> <td class="tg-c6of">{{transaction.cra_rate_from}}</td> </tr> <tr> <td class="tg-l8qj">Market Rent of the property :</td> <td class="tg-c6of">{{transaction.property_market_rent}}</td> </tr> <tr> <td class="tg-l8qj" >Number of Family Group(s) :</td> … -
Getting data from javascript ID to django views
how can I get data from javascript? lets say, my website show a input option, which I can't use with 'name="username"' like we do in forms, but it does that with document.getElementById('username') and show it later on site, is there anyway from which I can do the same with django? like request.POST.getById? I'm not good with english. -
Getting Django model.index has no field problem (django.core.exceptions.FieldDoesNotExist)
I am trying to create an index.The problem is that I am getting no 'has no field' error but I added that field. I tried to add that field but I got "column "click_count" of relation "oyunlar" already exists". How can i solve this situation? -
How can do not delete post and comment whose deleted user in django?
Hello i recently study django and make board my question was that how can do not delete post and comment whose deleted users how can display deleted user's name in post and comment like 'deleted user' in board's user name (not blank or Null) yeah i know in this code user was conneted with post and comment through foreign key and on_delete=models.CASCADE and if user deleted the post and comment deleted automatically then how can i connect this table? using nickname? it was unique but can changed i wanna know how to solve this problem, need to some tips class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField() create_date = models.DateTimeField(default= timezone.now()) def __str__(self): return self.title class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() create_date = models.DateTimeField(default=timezone.now()) -
VS Code not using selected python interpreter
What's up fellas. I always seem to have this problem and I've tried various ways of fixing it. Including creating the settings.json file that you can see in the picture attached. The problem: VS Code isn't using my selected python interpreter (pictured in the bottom left hand corner of photo) which is in venv/bin/python. Even though I can select it as the interpreter in vs code when I do python manage.py runserver for Django it gives me an error due to it using an older version of python that came with my computer. I just tried to use pycharm for the first time because of this and ended up having the same problem. Is it just that the terminal isn't using the right version of Python maybe? VS Code Version: 1.62.3 Also I am on iOS (M1) Let me know if I can provide you with any further information, thanks. [![Image of my vscode set up][1]][1] ➜ Akutagawa . venv/bin/activate (venv) ➜ Akutagawa which python /usr/bin/python (venv) ➜ Akutagawa which python /usr/bin/python (venv) ➜ Akutagawa cd Djanrest/backend (venv) ➜ backend git:(main) ✗ which python /usr/bin/python (venv) ➜ backend git:(main) ✗ python manage.py runserver File "manage.py", line 17 ) from exc … -
Добрый день, кто может подсказать как реализовать данную задумку на DJANGO REST
Схема работы: 1 Пользователь регистрируется в нашей системе. При регистрации указывает логин, пароль и имя 2 Пользователь находит бота в Telegram и подписывается на него. На этом этапе требуется создать Telegram бота. 3 В личном кабинете генерирует токен и привязывает этот токен к своему чату. Простой способ реализации: любое входящее сообщение от пользователя бот запоминает как токен пользователя 4 Пользователь отправляет на API своё сообщение. В этот момент бот сразу дублирует его в Telegram. Пользователь должен получать только свои сообщения. Добрый день, кто может подсказать как реализовать данную задумку на DJANGO REST, или же вы видели похожие проекты на github -
Django web project not running
My Web Application is not running on the new system it says it does not recognize "python"/ "pip as an internal and external command. My Powershell Terminal ''' PS C:\Users\Nawaf Bhatti\Desktop\learn> python -m pip install pillow python: The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + python -m pip install pillow + ~~~~~~ + CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ''' My cmd ''' C:\Users\Nawaf Bhatti\Desktop\learn\web_app>python manage.py runserver 'python' is not recognized as an internal or external command, operable program or batch file. ''' -
insert or update on table "django_admin_log" violates foreign key constraint
Trying to save a post on a django project I got this error The above exception (insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". ) was the direct cause of the following exception: The model: from django.conf import settings class Tag(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField() image = models.ImageField(upload_to='', blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title The view: from django.views.generic import ListView, DetailView from django.shortcuts import get_object_or_404 from .models import Post class BlogView(ListView): template_name = 'base/blog.html' queryset = Post.objects.all() paginate_by = 2 class PostView(DetailView): model = Post template_name = 'base/post.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs['pk'] slug = self.kwargs['slug'] post = get_object_or_404(Post, pk=pk, slug=slug) context['post'] = post return context How can I solve this problem? -
Able to run Dockerized Django app with supervisor locally, but timing out when deployed to Azure app services
So I have a Dockerized Django app running with uWSGI and NGINX, managed by supervisord (so both of them are run in the same container). It works fine and dandy when running it locally, but when I deploy it to a Azure web-app for containers, it fails to respond on the http warmup-request. I've tried doing different kinds of adjustments regarding the ports on Azure/in the app, but nothing seems to be working. The set-up I've been trying is: NGINX exposing the app in port 80, adding configuration in the Azure portal with PORT=80 NGINX exposing the app in port 8000, adding configuration in the Azure portal with PORT=80 and WEBSITES_PORT=8000 In both cases exposing both 80 and 8000 in the Dockerfile Increase the timeout-limit for the app to 1800 seconds But I'm still receiving the same error, and I really feeling I don't know where to go from here. Can anyone help me figure this one out? I'll post the logs and the relevant files below. As you can see in the logs, supervisor seems to be starting up, but not giving the response that Azure seems to need to start up the server. Repository structure myapp/ ┣ .devcontainer/ … -
Django making migrations
Consider the following three classes: class UUIDModel(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) class Meta: abstract = True class TimeStampedUUIDModel(UUIDModel): created = models.DateTimeField(auto_now_add=True, editable=False) modified = models.DateTimeField(auto_now=True, editable=False) class Meta: abstract = True class UsefulClass(TimeStampedUUIDModel): name = models.CharField(max_length=150, unique=True) creator = models.ForeignKey('OtherClass', on_delete=models.SET_NULL, null=True) Based on these classes, when I am running the makemigrations command, Django will create two migrations. One contains the id, created, modified and name (!) fields and the second one adds the creator foreign key. What could be the reason of the creation of two migrations, instead of just one? -
how do i get all my object instances as an int
i am creating a ToDo app and i want to calculate the percentage of activities completed based on the total activities set my views.py def progress(request): todo1 = int(ToDo.objects.all().count()) complete1 = int(ToDo.objects.filter(completed=True)) todo = int(todo1) complete = int(complete1) percent = complete // todo * 100 context = { 'percent' : percent, } return render(request, 'percent.html', context) but i receive a TypeError: int() argument must be a string, a bytes-like object or a number, not 'QuerySet' i really need help -
hello how to change string type into <class 'django.db.models.query_utils.Q'>
''' string = Q(run_date = '2016-05-01') & Q(distance__gt = 20) | Q(distance__lt = 10) data = Test_allowed.objects.filter(q_pickled) return HttpResponse(data) got error "too many values to unpack (expected 2)" because type is str ''' -
Django - Find reserved times
I would like to show all the available times for the not booked appointment dates with a time interval between 11:00AM to 21:00PM: models.py class Appointment(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) seat = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True) work = models.ManyToManyField(Therapy, related_name='work', verbose_name=_('Work'), blank=True) start_appointment = models.DateTimeField(default=timezone.now, blank=True) end_appointment = models.DateTimeField(default=timezone.now, blank=True) views.py def check_available_hours(request): day_request = date.today() day_request1 = str(day_request) date_of_reference = datetime.strptime(day_request1, "%Y-%m-%d") initial_time = datetime.combine(date_of_reference.date(), time(11, 0)) final_time = datetime.combine(date_of_reference.date(), time(21,0)) appointments_of_day = Appointment.objects.filter( start_appointment__gte=initial_time, start_appointment__lte=final_time ) print(appointments_of_day) # This returns all appointments in a day reserved_times = [datetime(2021, 12, 8, 11, 0), datetime(2021, 12, 8, 15, 0)] hours_between = [datetime.combine(date_of_reference.date(), time(hour + initial_time.hour, 0)) for hour in range(((final_time - initial_time).seconds // 3600) + 1)] available_hours = [hour for hour in hours_between if hour not in reserved_times] return render(request, "name_template.html", {"hours": avaliable_hours}) If i set reserved_dates like above it works. However i'm trying to set it based on my models so i used below code but it doesn't return anything. reserved_times = [ appointment.start_appointment + timedelta(hours=i) for appointment in appointments_of_day for i in range((appointment.end_appointment - appointment.start_appointment).seconds//3600)] print(reserved_times) Any suggestions? Thank you -
Django - Return only checked object from nested JSON
I have a problem returning checked data from html page views.py: First I open JSON file and store it to data from django.shortcuts import render from django.http import HttpResponse, request import json from fpdf import FPDF from django.db import models # Create your views here. #invalid = '<>:"//\t\|?*' url = 'podaci.json' class PDF(FPDF): def header(self): self.image('Logo_SAVA_osiguranje_RGB.png',w=60) self.ln(20) with open(url,encoding="utf8") as f: data=json.load(f) def remove(string, i): a = string[ : i] b = string[i + 1: ] return a + b def display_data(request): render(request,'home.html',{'data':data}) if request.method=='POST': for podatak in request.POST.getlist('checks'): print(podatak) return render(request,'home.html',{'data':data}) html: in HTML i set a value of Checkbox to be an object of data <body class="container"> <form method="post"> {% csrf_token %} <button type="submit">Submit</button> {% for duznici in data %} <div class="card"> <div class="card-header" > {{duznici.NazivDuznika}} <input class="form-check-input" type="checkbox" name="checks" value='{{data}}'> </div> <div class="card-body"> <blockquote class="blockquote mb-0"> {% for podaci in duznici.DunningItems %} <p name="checks" value="{{NazivDuznika}}">{{podaci.BrojPolise}}</p> {% endfor %} </blockquote> </div> </div> {% endfor %} </form> </body> podaci.json structure: [ { "NazivDuznika": "xxxxxxxx", "Pib": "xxxxxxxx", "Mtbr": "xxxxxxxx", "IdLica": xxxxxxxx, "Email": xxxxxxxx, "DunningItems": [ { "BrojPolise": "xxxxxxxx", "Broj_dokumenta_Z": "xxxxxxxx", "Dug": xxxxxxxx, "Datum_Dospeca_Z": "xxxxxxxx", "RbRate": xxxxxxxx, "VrstaOsiguranja": "xxxxxxxx", "Rocnost": xxxxxxxx }, { "BrojPolise": "xxxxxxxx", "Broj_dokumenta_Z": "xxxxxxxx", "Dug": xxxxxxxx, "Datum_Dospeca_Z": "xxxxxxxx", … -
Storing Data in Database without Tables (Because I don't need Entities/Objects) Django Models class
Let me Explain the Whole Question Correctly. I have a class called CData and I just want to store 6 values in it. I don't want different instances/Objects of it because it is global data that is not related to its instances i.e. Its static and should be accessed only by Class itself No objects are to be created. Model.py from django.db import models # Create your models here. class Patient(models.Model): name = models.CharField(max_length=100, default='') dob = models.DateField() fever = models.BooleanField(default=False) cough = models.BooleanField(default=False) headache = models.BooleanField(default=False) diarrhea = models.BooleanField(default=False) diarrhea = models.BooleanField(default=False) tasteless = models.BooleanField(default=False) def __str__(self): return self.name class CovidPatient(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) def __str__(self): return self.patient.name class CData: total = 0 covid = 0 treatment = 0 recovered = 0 dead = 0 discharged = 0 def total_patient(self): self.total = len(Patient.objects.all()) return self.total def add_patient(self, pid): patient = CovidPatient.objects.get_or_create(id = pid) self.covid += 1 return patient.name def covid_patient(self): return self.covid def under_treatment(self): self.treatment = len(CovidPatient.objects.all()) return self.treatment def add_recovered(self, cpid): patient = CovidPatient.objects.get(id = cpid) self.recovered += 1 patient.delete() def total_recovered(self): return self.recovered def add_dead(self, cpid): patient = CovidPatient.objects.get(id = cpid) self.dead += 1 patient.delete() def total_dead(self): return self.dead def add_discharged(self, cpid): patient = CovidPatient.objects.get(id = …