Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dockerized django container not producing local migrations file
Question I am a beginner with docker; this being the first project I have set up with it and don't particularly know what I am doing. I would very much appreciate if someone could give me some advice on what the best way to get migrations from a dockerized django app to store locally What I have tried so far I have a local django project setup with the following file structure: .docker -Dockerfile project -data -models - __init__.py - user.py - test.py -migrations - 0001_initial.py - 0002_user_role.py ... settings.py ... manage.py Makefile docker-compose.yml ... In the current state the migrations for the test.py model have not been run; so I attempted to do so using docker-compose exec main python manage.py makemigrations. This worked successfully returning the following: Migrations for 'data': project/data/migrations/0003_test.py - Create model Test But produced no local file. However, if I explore the file system of the container I can see that the file exists on the container itself. Upon running the following: docker-compose exec main python manage.py migrate I receive: Running migrations: No migrations to apply. Your models in app(s): 'data' have changes that are not yet reflected in a migration, and so won't be applied. … -
Django query in multiple table
I have 4 tables that contain data I want the query that will allow me to filter the policies according to the date and health center. Currently the code I filter the date but not the health center since they are not contained in the same table I do not know i I have to make a join or I just create a variable like what I did but that does not take. I have four models that can be used to show exactly how the tables are linked ` class Policy(core_models.VersionedModel): id = models.AutoField(db_column='PolicyID', primary_key=True) uuid = models.CharField(db_column='PolicyUUID', max_length=36, default=uuid.uuid4, unique=True) stage = models.CharField(db_column='PolicyStage', max_length=1, blank=True, null=True) status = models.SmallIntegerField(db_column='PolicyStatus', blank=True, null=True) value = models.DecimalField(db_column='PolicyValue', max_digits=18, decimal_places=2, blank=True, null=True) family = models.ForeignKey(Family, models.DO_NOTHING, db_column='FamilyID', related_name="policies") enroll_date = fields.DateField(db_column='EnrollDate') start_date = fields.DateField(db_column='StartDate') effective_date = fields.DateField(db_column='EffectiveDate', blank=True, null=True) expiry_date = fields.DateField(db_column='ExpiryDate', blank=True, null=True) product = models.ForeignKey(Product, models.DO_NOTHING, db_column='ProdID', related_name="policies") officer = models.ForeignKey(Officer, models.DO_NOTHING, db_column='OfficerID', blank=True, null=True, related_name="policies") offline = models.BooleanField(db_column='isOffline', blank=True, null=True) audit_user_id = models.IntegerField(db_column='AuditUserID') ` ` class InsureePolicy(core_models.VersionedModel): id = models.AutoField(db_column='InsureePolicyID', primary_key=True) insuree = models.ForeignKey(Insuree, models.DO_NOTHING, db_column='InsureeId', related_name="insuree_policies") policy = models.ForeignKey("policy.Policy", models.DO_NOTHING, db_column='PolicyId', related_name="insuree_policies") enrollment_date = core.fields.DateField(db_column='EnrollmentDate', blank=True, null=True) start_date = core.fields.DateField(db_column='StartDate', blank=True, null=True) effective_date = core.fields.DateField(db_column='EffectiveDate', blank=True, null=True) expiry_date … -
Error: Docker build failed cuando subo un proyecto Django a Railway
Estoy intentando subir mi proyecto Django a Railway, pero cuando lo esta subiendo me aparece el errpr de Error: Docker build failed Busque informacion de este error, pero aun no encuentro una solucion para esto Esto es una parte del Build Logs #11 6.938 Preparing metadata (setup.py): finished with status 'error' #11 6.945 error: subprocess-exited-with-error #11 6.945 #11 6.945 × python setup.py egg_info did not run successfully. #11 6.945 │ exit code: 1 #11 6.945 ╰─> [18 lines of output] #11 6.945 mysql_config --version #11 6.945 /nix/store/1b9p07z77phvv2hf6gm9f28syp39f1ag-bash-5.1-p16/bin/sh: line 1: mysql_config: command not found #11 6.945 mariadb_config --version #11 6.945 /nix/store/1b9p07z77phvv2hf6gm9f28syp39f1ag-bash-5.1-p16/bin/sh: line 1: mariadb_config: command not found #11 6.945 mysql_config --libs #11 6.945 /nix/store/1b9p07z77phvv2hf6gm9f28syp39f1ag-bash-5.1-p16/bin/sh: line 1: mysql_config: command not found #11 6.945 Traceback (most recent call last): #11 6.945 File "<string>", line 2, in <module> #11 6.945 File "<pip-setuptools-caller>", line 34, in <module> #11 6.945 File "/tmp/pip-install-mt5wgibs/mysqlclient_2b639a2efa944f928deea71cdfaf5c0c/setup.py", line 15, in <module> #11 6.945 metadata, options = get_config() #11 6.945 ^^^^^^^^^^^^ #11 6.945 File "/tmp/pip-install-mt5wgibs/mysqlclient_2b639a2efa944f928deea71cdfaf5c0c/setup_posix.py", line 70, in get_config #11 6.945 libs = mysql_config("libs") #11 6.945 ^^^^^^^^^^^^^^^^^^^^ #11 6.945 File "/tmp/pip-install-mt5wgibs/mysqlclient_2b639a2efa944f928deea71cdfaf5c0c/setup_posix.py", line 31, in mysql_config #11 6.945 raise OSError("{} not found".format(_mysql_config_path)) #11 6.945 OSError: mysql_config not found #11 6.945 [end of output] … -
Django server hangs sometimes
I am new to Django and I run into strange problem that the server hangs sometimes. The server uses APScheduler to do periodic tasks and send data to frontend via WebSocket. So, after the server freezes, I pressed CRTL+C to perform keyboard Interrupt. The server became normal again. I run the server in debug mode locally on my machine. But this problem only happens once or twice for the past two weeks. The rest of time it runs normally. The first time it happened when I tried to login. Application instance \<Task pending name='Task-1119' coro=\<StaticFilesWrapper.__call__() running at D:\\Python\\Python310\\lib\\site-packages\\channels\\staticfiles.py:44\> wait_for.\<Future pending cb=\[\_chain_future.\<locals\>.\_call_check_cancel() at D:\\Python\\Python310\\lib\\asyncio\\futures.py:385, Task.task_wakeup()\]\>\> for connection \<WebRequest at Ox25f4bObad70 method=POST uri=/admin/login/ clientproto=HTTP/1.1\> took too long to shut down and was killed The second time it happened when I tried to visit taskManager page. Application instance \<Task pending name='Task-153' coro=\<StaticFilesWrapper.__call__() running at D:\\Python\\Python310\\lib\\site-packages\\channels\\staticfiles.py:44\> wait_for.\<Future pending cb=\[\_chain_future.\<locals\>.\_call_check_cancel() at D:\\Python\\Python310\\lib\\asyncio\\futures.py:385, Task.task_wakeup()\]\>\> for connection \<WebRequest at Ox19fbb5140550 method=POST uri=/taskManager clientproto=HTTP/1.1\> took too long to shut down and was killed Python: 3.10.7 Django: 3.2 Channel: 3.0.5 And I am using InMemoryChannelLayer I am not sure if it jammed when trying to response GET or POST, or the server jammed first so it cannot process any … -
Django TypeError - context must be a dict rather than a set [closed]
I am trying to display certain objects to the user. The views.py method filters through the objects to get the ones we need and renders this using a template. However when doing this I receive a TypeError that context must be a dict rather than set. This is my views.py method def showings_view(request, performanceId): currbooking = Booking.objects.get(id=performanceId) l = shows.objects.filter(booking = currbooking) return render(request, 'show_list.html',{'l', l}) Edit: It says question closed due to a typo - could someone at least let me know what the typo is? -
How to enable or disable fields in a form according to previous answers?
I am working on the development of a web application with Django and the following question has arisen: I put an example: I am performing a registration and I want to know if the user who is registering has a phone number and in the case of having it that a field is enabled to enter it. In the case that he/she does not have it, he/she should not be able to enter it. Does anyone know how I can develop this option? Thanks in advance I tried to put an IF in the creation of the model but it did not work. -
Forward content from one html to another html via views.py
I try to send the content from 'addQuestion.html' to "approve_question.html" but i get the Error: approve_questions() missing 1 required positional argument: 'form' What i do False. I hpe someone can solve my issue views.py def question (request): form = addQuestionform() if (request.method == 'POST'): form = addQuestionform(request.POST) if (form.is_valid()): form.save(commit=False) html = render_to_string("notification_email.html") send_mail('The contact form subject', 'This is the message', 'noreply@codewithstein.com', ['example@gmail.com'], html_message=html) approve_questions(request, form) return redirect("dashboard") context = {'form': form} return render(request, 'addQuestion.html', context) def approve_questions(request, form): context = {'form' : form} return render(request, "approve_question.html", context) -
Clicking the button in the html template does not change the "status" field in the django model
everyone! I have models.py class Post(models.Model): ... status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='Activated') ... urls.py app_name = 'posts' urlpatterns = [ ... path('<int:pk>/update/', views.PostUpdateView.as_view(), name='update_status')] views.py class PostUpdateView(UpdateView): model = Post template_name = 'post_detail.html' def change_status(self): if request.method == "POST": post = Post.objects.filter(id=self.id) if post.status == 'Activated': post.status = 'Deactivated' post.save() elif post.status == 'Deactivated': post.status = 'Activated' post.save() return redirect('posts:post_detail') posts_detail.html ... <form action="{% url 'posts:update_status' post.id %}" method="post"> {% csrf_token %} <button type="button"> {% if post.status == 'Activated' %} Deactivate {% else %} Activate {% endif %}</button> </form> ... I want to switch the field on the button "Activate/Deactivate" and redirect to the same page. At the moment there is a button and when clicked nothing changes. Well or maybe the redirect works, but the status does not switch. I'm assuming wrong views.py, but can't figure out where. I tried it like this @require_http_methods(['POST']) def update_status(request, id): if post.status == 'Activated': Post.objects.filter(id=id).update(status='Deactivated') elif post.status == 'Deactivated': Post.objects.filter(id=id).update(status='Activated') return redirect('posts:post_detail') But that doesn't work either. I know these are similar ways, but I don't have any more ideas. -
Django admin inline and multiple queries
I'm optimizing Django admin, and have some issues with inlines. I saw a few questions from Stack Overflow, but none was helpful. Here is my code: models/consumer_application.py class ConsumerApplication(TimeStampedModel, ActivatorModel, HumanReadableIdModel): uuid = models.UUIDField(default=uuid.uuid4, db_index=True, unique=True) status = models.ForeignKey("consumer.ApplicationStatus", on_delete=models.PROTECT) ... models/offer.py class ConsumerApplication(TimeStampedModel, ActivatorModel, HumanReadableIdModel): uuid = models.UUIDField(default=uuid.uuid4, db_index=True, unique=True) application = models.ForeignKey("consumer.ConsumerApplication", on_delete=models.PROTECT, related_name="offers") ... admin.py @admin.register(ConsumerApplication) class ConsumerApplicationAdmin(UserInlineCustomAdminMixin, AddNewDisabled, admin.ModelAdmin): exclude = [...] list_display = (...) search_fields = (...) readonly_fields = (... ) inlines = [OfferInline] def get_queryset(self, request): return super().get_queryset(request).prefetch_related("offers") class OfferInline(admin.TabularInline): model = Offer exclude = [...] And when I open ConsumerApplication detail view, I have 6 offers displayed, and 12 queries: SELECT "consumer_offer"."id", "consumer_offer"."application_id" FROM "consumer_offer" WHERE "consumer_offer"."id" = 675 LIMIT 21 I was trying to override get_queryset of OfferInline, but whatever I did, I get the same. How can I optimize it, so that I don't have these 12 queries? -
Overriding django admin pagination along with dynamic values
I am working on a project, I have a requirement from my client he wants to implement a dynamic paginator in django admin panel. Requirement is when user input 10, ten record will display per page same for 20,30 is there any way to do it. -
Argon2 password hashing in django
i noticed my django is hashing the passwords asargon2$argon2id$v=19$m=102400,t=2,p=8$salt$hash according to Argon2 in browser the encription is $argon2id$v=19$m=102400,t=2,p=8$salt$hash if i try to match argon2$argon2id$v=19$m=102400,t=2,p=8$salt$hash to the actual password it will not match, but if i test it against $argon2id$v=19$m=102400,t=2,p=8$salt$hash it matches Is there a way that i can hash a password to argon2$argon2id$v=19$m=102400,t=2,p=8$salt$hash offline so it will work if i replace it in the database of django? -
I am trying to create a circle progress bar, but I can not access the javascript variables, why?
I am working with tailwind.css in my Django HTML template. I am trying to recreate this circle https://tailwindcomponents.com/component/circular-progress-bar, but I am not rolling my screen, I am setting a static percentage based on a value from my view. This average rate calculation does not matter, this is working in another part, it is just an example to show what I want to do in my radial bar. class RatePage(TemplateView): template_name = "tailwind/rate-page.html" def get_context_data(self, **kwargs): context = super(RatePage, self).get_context_data(**kwargs) context['average_rate'] = 4.5 return context This is my HTML template. <div class="flex flex-col"> Score <svg class="w-20 h-20"> <circle class="text-gray-300" stroke-width="5" stroke="currentColor" fill="transparent" r="30" cx="40" cy="40" /> <circle class="text-blue-600" stroke-width="5" :stroke-dasharray="circumference" :stroke-dashoffset="circumference - percent / 100 * circumference" stroke-linecap="round" stroke="currentColor" fill="transparent" r="30" cx="40" cy="40" /> </svg> <span class="absolute text-xl text-blue-700" x-text=30></span> </div> <script> let percent = rate; let circumference = 2 * Math.PI * 30; </script> I am trying to connect JavaScript with the rate value from view to make this calculus. But, everything I am getting is this: But, I am trying to do it: Any suggestion? -
Django TemplateSyntaxError - for loop counter issue
I am attempting to call a function in my Django template. This function is called within a forloop and the function should take the loop index (counter of sorts) as its parameter. Below is the template code for which I am receiving an issue. {% for showing in show.num_of_performances %} {% with index=forloop.counter0 %} <tr> <td> {{ show.next(index) }} </td> <td> {{ show.performer }} </td> </tr> {% endwith %} {% endfor %} The error I am receiving is: TemplateSyntaxError at /showing_list/2/ Could not parse the remainder: '(index)' from 'show.next(index)'. I had tried just putting 'forloop.counter0' in the parentheses for show.next initially but received a similar error and so have been trying this but it does not seem to be working no matter what I try. -
Unpacking a JSONField into multiple django forms fields to update with UpdateView
l'm new to Django and don't understand what exactly i need to do to update my JSONfield in django model. models.py: class Schemas(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=15) modified = models.DateField() column_separator = models.CharField(max_length=1) string_character = models.CharField(max_length=1) json_data = models.JSONField() forms.py: class UpdateSchemaForm(forms.ModelForm): class Meta: model = Schemas fields = ['title', 'column_separator', 'string_character', 'json_data'] views.py: class UpdateSchema(UpdateView): model = Schemas form_class = UpdateSchemaForm template_name = 'updateschema.html' success_url = 'home' I have a form where user can add new fields and fill them with data. enter image description here Then these fields save in JSONfield in models.py I want to allow user to update the JSONfield using UpdateView like making the same forms but filed. -
Views return html from another app in Django
I want to show a data with different feature .. So, there's 2 role where admin have 5 column on table when the teacher only have 4 column on table. I change the HTML already but when i return classlist.html on teacherpage views.py .. it return the admin classlist.html that have 5 column on the table. Here is my code : Urls.py (Teacher APP): from django.urls import path from teacherpage import views urlpatterns = [ path('', views.index, name='index'), path('classlist/', views.classlist, name='classlist'), ] Views.py (Teacher APP): def classlist(request): data = classModel.objects.all() classlist= { "classlist" : data } return render(request,'classlist.html', classlist) -
How to fix Django N+1 problem when you need to get data from a set of objects
I created a function and I wrote a query that results in N+1 Problem how to fix it code sponsors = CustomUser.objects.filter(user_type = 2, is_deleted = False) for s in sponsors: s.sponsor_detail = Sponsor.objects.get_or_create(user = s, is_deleted = False) -
Server Running Issue in Django. Ubuntu
I'm trying to display something on django server but Nothing is happening. I'm facing this error: "snapcraft.io store API service - Copyright 2018-2022 Canonical." I tried Everything But nothin... work. Please tell me correct solution :( I Tried This | python manage.py runserver [::]:8000 |, python manage.py runserver 0.0.0.0:8000 |, sudo nmap -sT -O localhost #to install=> sudo apt-get install nmap -
What is the best Way to modify PDF in Django?
Actually I want to modify PDF which is Certificate need to change name, date, course name and course description. I have tried the pypdf2 but doesn't work for me. Here is What i tried so far pdfFileObj = open('/home/nawaf/Documents/5_dec_truck_courses/29_Nov_Updated/truck_courses/LMS_Online_App/static/certificate.pdf', 'rb') pdf_reader = PdfFileReader(io.BytesIO(pdfFileObj.read())) pdf_page = pdf_reader.pages[0] pdf_text = pdf_page.extractText() change_name = pdf_text.replace("John Doe", "Nawaf").replace("NAME OF THE COURSETO","Rent Everything").replace("The course description will go her.","My Own Description") pdfFileObj.close() pdf_writer = PdfFileWriter(pdfFileObj) with open('/home/nawaf/Documents/5_dec_truck_courses/29_Nov_Updated/truck_courses/test/test.pdf', 'wb') as f: pdf_writer.addPage(page=pdf_page) pdf_writer.add_annotation(page_number=0, annotation=pdf_reader.metadata) pdf_writer.write(f) f.close() -
Page contents in Navbar not filling the screen:
Click here for image of problem Basically I sourced the code from getbootstrap.com but the search bar and search button are not being right-aligned in the navbar. Have tried to selectively align the search option but to no avail. Would live it if anyone helped. Thank you. Here is the code: ``` <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> ``` -
Wagtail add functions to models.py
i'm trying to make a custom plotly-graphic on a wagtail homepage. I got this far. I'm overriding the wagtail Page-model by altering the context returned to the template. Am i doing this the right way, is this possible in models.py ? Thnx in advanced. from django.db import models from wagtail.models import Page from wagtail.fields import RichTextField from wagtail.admin.panels import FieldPanel import psycopg2 from psycopg2 import sql import pandas as pd import plotly.graph_objs as go from plotly.offline import plot class CasPage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body'), ] def get_connection(self): try: return psycopg2.connect( database="xxxx", user="xxxx", password="xxxx", host="xxxxxxxxxxxxx", port=xxxxx, ) except: return False conn = get_connection() cursor = conn.cursor() strquery = (f'''SELECT t.datum, t.grwaarde - LAG(t.grwaarde,1) OVER (ORDER BY datum) AS gebruiktgas FROM XXX ''') data = pd.read_sql(strquery, conn) fig1 = go.Figure( data = data, layout=go.Layout( title="Gas-verbruik", yaxis_title="aantal M3") ) output = plotly.plot(fig1, output_type='div', include_plotlyjs=False) # https://stackoverflow.com/questions/32626815/wagtail-views-extra-context def get_context(self, request): context = super(CasPage, self).get_context(request) context['output'] = output return context -
Nginx: "The requested resource was not found on this server."
I have a Django app listening at 127.0.0.1:8000, my Nginx config is simply location / { proxy_pass http://127.0.0.1:8000; proxy_ssl_server_name on; } Everything works as expected. But then I changed the configuration to location /xxx { proxy_pass http://127.0.0.1:8000; proxy_ssl_server_name on; } I got error "The requested resource was not found on this server" when trying to access the website with "/xxx". What might be the problem? -
How to access Django parent model using Foreign key
I have this model: class Cohort(models.Model): id = models.AutoField(primary_key=True,editable=True) origin=models.BooleanField(default=False) title = models.CharField(max_length=200,validators=[MaxLengthValidator(100)]) email = models.ForeignKey(Userdata, on_delete=models.PROTECT,default='0',db_constraint=False) def __str__(self): return self.title class Subcohort(models.Model): cohort_id=models.ForeignKey(Cohort,on_delete=models.PROTECT,default=0,db_constraint=False,related_name='subcohortid') parent_id=models.ForeignKey(Cohort,on_delete=models.PROTECT,default=0,db_constraint=False,related_name='subparentid') From views.py I want to read Cohort model data using the subcohort cohort_id. I want to get an object which contains cohort data along with subcohort data. Can someone help? Thank you. -
How to use .get(id=some_model_field) in Model constraints?
I have class 'Car' class 'EngineType' and i want to add to it constraints. I want to check what type of engine is in the car, so i tried: models.CheckConstraint(check=(Q(EngineType.objects.get(id=engine_type).name=='electric')), name='test_constraint') where 'engine_type' is foreign key to EngineType. It gives me this error: NameError: name 'engine_type' is not defined. Did you mean: 'EngineType'? Constraints perfectly works without .get(), e.g. models.CheckConstraint(check=(Q(engine_type=1)), name='test_constraint2'), so it means that there is access to the 'engine_field' from constraints, but i have to check current engine type, not static. Any help would appreciate! 'Car' and 'EngineType' listing without some other fields: class EngineType(models.Model): name = models.CharField(max_length=100) class Car(models.Model): engine_type = models.ForeignKey(EngineType, on_delete=models.PROTECT) class Meta: constraints = [ models.CheckConstraint(check=(Q(EngineType.objects.get(id=engine_type).name=='electric')), name='test_constraint') ] Django automatically adds 'id to foreign key fields, i tried to replace in .get() 'engine_type' to 'engine_type_id', but got the same error with 'engine_type' replaced to 'engine_type_id'. -
Python Django Error: FileNotFoundError: [Errno 2] No such file or directory: '/proc/393/task/558'
I receive this error. It is happening during regular requests from front end, previous request has response 200, but then my backend container is suddenly reloading. Previously it was working and everything worked well. Django version 3.2.13 Python version 3.9 Cloud AWS Traceback: Traceback (most recent call last): File "/app/manage.py", line 21, in <module> main() File "/app/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 638, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 623, in start_django reloader.run(django_main_thread) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 329, in run self.run_loop() File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 335, in run_loop next(ticker) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 375, in tick for filepath, mtime in self.snapshot_files(): File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 391, in snapshot_files for file in self.watched_files(): File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 294, in watched_files yield from directory.glob(pattern) File "/usr/local/lib/python3.9/pathlib.py", line 1177, in glob for p in selector.select_from(self): File "/usr/local/lib/python3.9/pathlib.py", line 611, in _select_from for p in successor_select(starting_point, is_dir, exists, … -
Queryset filter
i whant to count a number of policy that have the status 2 and filter by date and by health_facilities i have 4 tables this are the model class Policy(core_models.VersionedModel): id = models.AutoField(db_column='PolicyID', primary_key=True) uuid = models.CharField(db_column='PolicyUUID', max_length=36, default=uuid.uuid4, unique=True) stage = models.CharField(db_column='PolicyStage', max_length=1, blank=True, null=True) status = models.SmallIntegerField(db_column='PolicyStatus', blank=True, null=True) value = models.DecimalField(db_column='PolicyValue', max_digits=18, decimal_places=2, blank=True, null=True) family = models.ForeignKey(Family, models.DO_NOTHING, db_column='FamilyID', related_name="policies") enroll_date = fields.DateField(db_column='EnrollDate') start_date = fields.DateField(db_column='StartDate') effective_date = fields.DateField(db_column='EffectiveDate', blank=True, null=True) expiry_date = fields.DateField(db_column='ExpiryDate', blank=True, null=True) product = models.ForeignKey(Product, models.DO_NOTHING, db_column='ProdID', related_name="policies") officer = models.ForeignKey(Officer, models.DO_NOTHING, db_column='OfficerID', blank=True, null=True, related_name="policies") offline = models.BooleanField(db_column='isOffline', blank=True, null=True) audit_user_id = models.IntegerField(db_column='AuditUserID') class InsureePolicy(core_models.VersionedModel): id = models.AutoField(db_column='InsureePolicyID', primary_key=True) insuree = models.ForeignKey(Insuree, models.DO_NOTHING, db_column='InsureeId', related_name="insuree_policies") policy = models.ForeignKey("policy.Policy", models.DO_NOTHING, db_column='PolicyId', related_name="insuree_policies") enrollment_date = core.fields.DateField(db_column='EnrollmentDate', blank=True, null=True) start_date = core.fields.DateField(db_column='StartDate', blank=True, null=True) effective_date = core.fields.DateField(db_column='EffectiveDate', blank=True, null=True) expiry_date = core.fields.DateField(db_column='ExpiryDate', blank=True, null=True) offline = models.BooleanField(db_column='isOffline', blank=True, null=True) audit_user_id = models.IntegerField(db_column='AuditUserID') class Insuree(core_models.VersionedModel, core_models.ExtendableModel): id = models.AutoField(db_column='InsureeID', primary_key=True) uuid = models.CharField(db_column='InsureeUUID', max_length=36, default=uuid.uuid4, unique=True) family = models.ForeignKey(Family, models.DO_NOTHING, blank=True, null=True, db_column='FamilyID', related_name="members") chf_id = models.CharField(db_column='CHFID', max_length=12, blank=True, null=True) last_name = models.CharField(db_column='LastName', max_length=100) other_names = models.CharField(db_column='OtherNames', max_length=100) gender = models.ForeignKey(Gender, models.DO_NOTHING, db_column='Gender', blank=True, null=True, related_name='insurees') dob = core.fields.DateField(db_column='DOB') dead = models.BooleanField(db_column='Dead') dod = core.fields.DateField(db_column='DOD', …