Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Operation error: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed')
I can not start my django server after running a statement through manage.py for generating class diagrams from db. And I always get this error but I don't know how to deal with it. OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed') I have tried re-install all the modules relevant to mysql for django but it was useless. -
django middleware return response and prevent calling main function
I want to use a form of cache using django middleware/context-processors. I do know it's simpler to just add the decorator at the top of the function but for reasons I have to do it this way. Using this as my example of my function def cache_results(request): response = {} if request.path == '/about': #my json response return {...} return response the idea is if it matches my requests it returns a result and also prevent the matching function call from the urls.py from being called or returning the result basically acting as a middleware caching system. Is this doable? -
What is the purpose of an input hidden tag in my login template when I implement a built-in login template in Django 2.0?
If you see my urls.py of my project, Why the login view hasn't a next_page parameter and my logout view has it? My instructor of Udemy doesn't explain well my curiosity of how the login view redirect to another template when the user is authenticated and when the user logout. If you see in my second image, login.html; The instructor said that is required an input hidden tag in my login template, but he doesn't explain why? I comment this line and my project works well too. I would appreciate if someone teach me the differents. -
Django: how to change the value of a field one changing another?
I have 2 fields in a model I need that when I change the value of a field to calculate the other Example: Date_mission1_equipe=models.DateField (null=True,blank=True,max_length=200) Date_mission2_equipe=models.DateField (null=True,blank=True,max_length=200) for example if i choose 01/01/2019 for Date_mission1_equipe automatically Date_mission2_equipe should be 02/01/2019 -
Showing a total of items created in a Django model
My Django project contains a task manager with Projects and Tasks, I have generic list page showing a list of all projects with information on their total tasks: class IndexView(generic.ListView): template_name = 'projects/index.html' context_object_name = 'project_list' def get_queryset(self): """Return 10 projects.""" return Project.objects.order_by('is_complete')[:10] I would like to display on my list page the total number of added projects and tasks, but I'm unsure how I should go about this. All by current work has been around listing the number of tasks that are included i each project, but now I want a total - should I add this as a new View? For example, I tried adding this to the view above: def total_projects(self): return Project.objects.count() Then calling {{ project_list.total_projects }} on my template, but it doesn't return anything. Is Views the correct place to do this? -
Django how use in template list of queryset
I'm a beginner in Django. I have these three classes class Escape(models.Model): name = models.CharField(max_length=100, unique=False) def __str__(self): return self.name class Salle(models.Model): salle = models.CharField(max_length=100, unique=False) escape = models.ForeignKey(Escape, on_delete=models.CASCADE) def __str__(self): return self.salle class Enigme(models.Model): enigme_name = models.CharField(max_length=100, unique=False) salle = models.ForeignKey(Salle, on_delete=models.CASCADE) def __str__(self): return self.enigme_name I try to display in my template a list of enigme for each salle. I cannot figure out how to build my view to display each set of enigme for each salle. This is my view : def salle_escape(request): escape_named = 'NumW' list_salle = Salle.objects.filter(escape__name=escape_named) enigme = [] for e in list_salle: enigme.append( Enigme.objects.filter(salle__salle=e) ) # enigme = Enigme.objects.filter(salle__salle= context = { 'escape' : Escape.objects.get(name=escape_named), 'salle' : list_salle, 'enigme' : enigme, } return render(request, 'chat/salle_escape.html', context) This my template : <!-- chat/templates/chat/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <h1>{{ escape.name }}</h1> <h2>Liste des salles</h2> <ul> {% for s in salle %} <li>{{ s.salle }} {{ forloop.counter0 }}</li> {% endfor %} </ul> {{ enigme }} </body> </html> In my browser displays for {{ enigme }} this : [<QuerySet [<Enigme: Lanterne>, <Enigme: Coussin>, <Enigme: Biblot>]>, <QuerySet [<Enigme: Operation>, <Enigme: Cle triangle>, <Enigme: Miroir>, <Enigme: Lumiere>]>, <QuerySet [<Enigme: Oiseau>, <Enigme: … -
How to fix "Page not found(404)" error in Django?
I am trying to build a restaurant site for learning Django. The site is very much simple but I am trying to make the site little dynamic. For eg: When users clicks Lunch, the url changes to "http://127.0.0.1:8000/menu/Lunch/" and lunch menu is displayed and so on (of course I am making a single template file to handle this). I have done the following implementation and I am getting "Page not Found(404)" error. Help me out please. My urls.py looks like this: urlpatterns = [ path('', views.index, name="index"), path('menu/', views.menu, name="menu"), path('menu/<str:menu_category>/', views.menu_detail, name="menu_detail"), ] My views.py looks like this: def menu_detail(request, menu_category): menu_list = get_list_or_404(Menu, category=menu_category) menu_title = Menu.objects.get(category=menu_category) return render(request, 'restaurant/menu_detail.html', {'menu_list': menu_list, 'menu_title': menu_title}) Also, I have made menu_detail.html file under "restaurant/templates" and I have correct path set in settings.py. -
Simple Django form and get value submitted
I would like to create a Django form very easy, than I would like to pick up the value from both fields. This is my form : class SettingsForm(forms.Form): download_validity = forms.CharField(label='Expiry Download') flag_validity = forms.CharField(label='Expiry Flag') def __init__(self, *args, **kwargs): super(SettingsForm, self).__init__(*args, **kwargs) Then, I have a view : class SettingsView(FormView): template_name = 'settings.html' form_class = SettingsForm def get_context_data(self, **kwargs): subtitle = _("Manage Settings") context_data = super(SettingsView, self).get_context_data(**kwargs) context_data['subtitle'] = subtitle return context_data def form_valid(self, form): download_validity = form.cleaned_data['download_validity'] flag_validity = form.cleaned_data['flag_validity'] print(download_validity) print(flag_validity) return super(SettingsView, self).form_valid(form) And finally my template view : {% block main %} <div class="container"> <div class="row"> <form autocomplete="off" method="get" action=""> <fieldset> <legend class="title"><span class="name">{% trans 'Expiry Download link' %}</span></legend> </fieldset> {{ form.download_validity|as_crispy_field }} <input type="submit" class="btn btn-default" name="UpdateDownload" value="{% trans 'Update' %}"/> </form> </div> <div class="row"> <form autocomplete="off" method="get" action=""> <fieldset> <legend class="title"><span class="name">{% trans 'Expiry New Publication' %}</span></legend> </fieldset> {{ form.flag_validity|as_crispy_field }} <input type="submit" class="btn btn-default" name="UpdateFlag" value="{% trans 'Update' %}"/> </form> </div> </div> {% endblock main %} I don't know why, but I would like to get value thanks to cleaned_data but the print function doesn't display anything. I don't know if I missed something but all seems to be right. I … -
Unit test to a view with post request and a CKEditor form in it
I have a view that submits a post and it contains a form that uses CKEditor as a part of this form, here is the form from forms.py class CreateAdminPostForm(forms.ModelForm): content = forms.CharField(widget=CKEditorUploadingWidget()) title = forms.CharField( widget=forms.TextInput( attrs={ 'placeholder': 'Post Title', 'class': 'form-control', 'style': 'max-width: 800px;', 'maxlength': '160', } ) ) keyword = forms.CharField( widget=forms.TextInput( attrs={ 'placeholder': 'Focus Keyword', 'maxlength': '60', } ) ) slug = forms.CharField( widget=forms.TextInput( attrs={ 'placeholder': 'Slug', 'maxlength': '60', } ) ) description = forms.CharField( widget=forms.Textarea( attrs={ 'placeholder': 'Post Description , Will be used as the Meta description for the post page', 'style': 'height: 370px;', 'maxlength': '160', } ) ) class Meta: model = Post fields = ['title', 'content', 'slug', 'keyword', 'category', 'description', 'featured_image'] and here is the view I use in views.py def admin_post(request): current_user = request.user current_author = Author.objects.get(user=current_user) create_admin_post_form = CreateAdminPostForm(request.POST, request.FILES) if request.method == 'POST': if create_admin_post_form.is_valid(): form = create_admin_post_form.save(commit=False) form.active = True form.email_active = True form.author = current_author form.save() return redirect('home') else: create_admin_post_form = CreateAdminPostForm() context = { 'create_admin_post_form': create_admin_post_form, } return render(request, 'admin_post.html', context) And finally here is the way I tested it in my tests class TestAdminPost(TestCase): def test_admin_post_view(self): response = self.client.get(reverse('admin_post')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'admin_post.html') def test_admin_post_empty(self): response … -
django: how to make StaticLiveServerTestCase listen on a particular port?
I have an app use vue as frontend and django rest framework as backend. In my app, the vue run on port 8080, and django run on port 8000, how could I make StaticLiveServerTestCase listen on the vue server's port? -
Django query error: int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta'
I'm gonna get records which person lives less than 1 month. cnt = Personne.objects.annotate( duration=Func(Func(F('deces_an_grg'), F('deces_mois_grg'), F('deces_jour_grg'), function='make_date'), Func(F('date_declaration_an_grg'), F('date_declaration_mois_grg'), F('date_declaration_jour_grg'), function='make_date'), function='age') ).filter(duration__gt=timedelta(days=30)).count() -
Django whoosh search with no results in language version
I have Django app with whoosh as search engine. I have also two language version - English and German. I made rebuild_index and update_index. Only English version is working but in German version I have no results. Size of folders on server (after rebuild_index and update_index): whoosh_index_de - 3 MB whoosh_index_en - 190 MB settings configuration: HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'search.backend.MultilingualWhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index_de'), }, 'default_de': { 'ENGINE': 'search.backend.MultilingualWhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index_de'), }, 'default_en': { 'ENGINE': 'search.backend.MultilingualWhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index_en'), }, } Has somebody similar problem? -
django.db.utils.OperationalError: foreign key mismatch in Shell command forloop
I am working on the following two Django models: Organisation model which has the User as Foreign key and the Category list which has the Organisation as its Foreign Key Following are the Models: # Create your models here. from django.contrib.auth.models import User from django.db import models class Organisation(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True ) organisation_name = models.TextField( primary_key=True, blank=True ) def __str__(self): return self.organisation_name class Category(models.Model): organisation = models.ForeignKey( Organisation, on_delete=models.SET_NULL, null=True ) category = models.TextField( blank=True, max_length=200 ) class Meta: verbose_name_plural = 'Category' Now I have got a huge list of 150+ values stored in my settings.py file which I want to add within the Category model. The CATEGORY_LIST = ['value', 'value2', ...., 'valueN'] looks like this This is the script I am executing in shell: from Venter.models import Organisation, Category from Backend import settings cat_list = settings.CATEGORY_LIST # the list is getting loaded into cat_list org_name = Organisation.objects.get(organisation_name='ABC') # exists for x in cat_list: Category.objects.create(organisation=org_name, category=x) However I am encounter the following error: django.db.utils.OperationalError: foreign key mismatch - "Mysite_category" referencing "Mysite_organisation" where: Mysite is my app name in Django project. Please help! Thanks -
Django: How to redirect users to pages based on form input?
I am creating a webpage that should redirect its users to a subpage, based on their choices in a form with radio buttons. The radio button input should trigger logic calculations. For example: Form with example user input (Yes/No): [Question] | [Yes] | [No] Question1 | ------ | XXX Question2 | ------ | XXX Question3 | XXX | ------ Logic: If Q1=No, Q2=No and Q3=Yes, then redirect to page W If Q1=Yes, Q2=No and Q3=Yes, then redirect to page X If Q2=Yes, then redirect to page Y Else, then redirect to page Z The webpage is part of a project created using Django and Python. I do not know how to approach this problem, as the form input should be passed to the webserver while maintaining the possibility to perform the logic calculations. Also, I do not want to store the user input to my database. After a user has been redirected to page W, X, Y or Z, no input should be memorized. Can you please help me in finding a proper way to post the user form data to the server, perform the logic calculations and using the result to redirect the user to the right page? Thank … -
How to get permission list using Keycloak Token
Can't get the User Permission list using Keycloak token. Getting error like keycloak.exceptions.KeycloakAuthorizationConfigError: Keycloak settings not found. Load Authorization Keycloak settings. Iam using python-keycloak Keycloak Configuration keycloak_openid = KeycloakOpenID(server_url=config.server_url, client_id=config.client_id, realm_name=config.realm_name, client_secret_key=config.client_secret_key, verify=True) keycloak_openid.load_authorization_config(os.path.join(local_path, 'Dynamic_Client-authz-config.json')) userinfo = keycloak_openid.get_permissions(token, method_token_info='introspect') print(userinfo) Key Cloak Setting File { "allowRemoteResourceManagement": false, "policyEnforcementMode": "PERMISSIVE", "resources": [ { "name": "Default Resource", "type": "urn:Dynamic_Client:resources:default", "ownerManagedAccess": false, "attributes": {}, "_id": "2c2a046f-84b2-42a8-a028-c6ae56ad63a1", "uris": [ "/*" ] } ], "policies": [ { "id": "f570c7e7-8168-4fb8-b05c-4df8be9398d0", "name": "Default Policy", "description": "A policy that grants access only for users within this realm", "type": "js", "logic": "POSITIVE", "decisionStrategy": "AFFIRMATIVE", "config": { "code": "// by default, grants any permission associated with this policy\n$evaluation.grant();\n" } }, { "id": "836d2453-ad1c-4482-b726-49875a8ba64f", "name": "Default Permission", "description": "A permission that applies to the default resource type", "type": "resource", "logic": "POSITIVE", "decisionStrategy": "UNANIMOUS", "config": { "defaultResourceType": "urn:Dynamic_Client:resources:default", "applyPolicies": "[\"Default Policy\"]" } } ], "scopes": [] } Please find the solution for my issue -
Delete Record Before Save
i want to delete all the records which having the company.id in model AclRoleAccess AclRoleAccess(models.Model): acl_role = models.ForeignKey(ACLRoles, on_delete=models.CASCADE) acl_company = models.ForeignKey(Company, on_delete=models.CASCADE) acl_functionality = models.ForeignKey(AclFunctionality, on_delete=models.CASCADE) acl_has_access = models.BooleanField() class Meta: db_table = "acl_role_accesses" @receiver(pre_save, sender=AclRoleAccess) def delete_AclRoleAccess(sender, instance, update_fields=None, **kwargs): print('Delete These', instance) -
How to fill empty fields when I save form from POST
I try to fill empty fields when I save model form, but unfortunately, it doesn't work properly. this is my view: def bylaw_save(request): form = BylawForm(initial={'who_created': request.user.username}) if request.method == 'POST': form = BylawForm(request.POST) if form.is_valid(): gdn = GlobalDocNumber.objects.get(pk=1) gdn.gdn += 1 gdn.save() raspr_num = form.cleaned_data['raspr_num'][:] raspr_num = raspr_num.split('/') bylaw = form.save(commit=False) bylaw.district = 'unfilled' bylaw.department = 'unfilled' bylaw.performer = 'unfilled' bylaw.check_type = 'unfilled' bylaw.save() return bylaw_form(request, msg='test') else: return bylaw_form(request, msg='test') return render(request, 'bylaw/bylaw_form.html', {'form': form}) this is fraction of my form: district = ModelChoiceField(required=False, queryset=DistrictsMenu.objects.all(), to_field_name="district", widget=Select(attrs={'id': "district", 'class': 'form-control col-6'})) department = ModelChoiceField(required=False, queryset=DepartmentsMenu.objects.all(), to_field_name="department", widget=Select(attrs={'id':"department", 'class': "form-control col-6"})) when I save this from, it always fills with 'unfilled'. How can I fill empty values only if they are really empty? -
API endpoint URL with <id> or without?
What approach is recommended? API endpoint URL with or without? /api/orders/<id>/ def post(self, request, id): order = get_object_or_404(Order, pk=self.kwargs.get('id'), company=request.user.company) ... or /api/orders/ def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): order_id = serializer.validated_data.get('order_id') order = Order.objects.get(pk=order_id) if order.user.company != request.user.company: raise Http404 .... -
Please, how do i resolve the validation error at admin("" value must be an integer)
Whenever i launch the server and i try to access the admin page, i often get the ValidationError: ['test@user.com' value must be an integer]. I had created custom user for the project and done the necessary settings(admin.py,model.py,forms.py) as instructed in the documentation. I have also tried to write an authentification backend in settings.py but lead to another error. But could not figure out why the pk is using USERNAME_FIELD as the pk. class User(AbstractBaseUser): user_id = models.AutoField(primary_key=True,unique=True) username = models.CharField(max_length=50,unique=True) first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50,blank=True,null=True) email = models.EmailField( max_length=200, unique=True, ) date_joined = models.DateTimeField(default=timezone.now) # confirm = models.BooleanField(default=False) # confirm_date = models.DateTimeField(default=False) # phone_no = models.IntegerField(max_length=40) state = models.CharField(max_length=50,blank=True,null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] Traceback: File "C:\Users\Ayo Paul\.virtualenvs\python_and_Django_web_development-NQaQovYW\lib\site-packages\django\db\models\fields\__init__.py" in to_python 940. return int(value) During handling of the above exception (invalid literal for int() with base 10: 'test@user.com'), another exception occurred: File "C:\Users\Ayo Paul\.virtualenvs\python_and_Django_web_development-NQaQovYW\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\Ayo Paul\.virtualenvs\python_and_Django_web_development-NQaQovYW\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\Ayo Paul\.virtualenvs\python_and_Django_web_development-NQaQovYW\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ayo Paul\.virtualenvs\python_and_Django_web_development-NQaQovYW\lib\site-packages\django\contrib\admin\sites.py" in wrapper 241. return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Users\Ayo Paul\.virtualenvs\python_and_Django_web_development-NQaQovYW\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. … -
Facing issue in deploying opencv django application in AWS
I have developed a simple object detection application using opencv, python3 and tensorflow using cpu. I have converted as web services and the "GET" request runs locally well. It initiates the camera for live video streaming. Then I have deployed the app in AMazon instance using Elastic Beanstalk . the request is running but it takes too much time and it says memory insufficient error. the aws log says the error adn i tried running simple opencv code to open laptop camera. but the log says NO VIDEO CAMERA FOUND IN 0.. Please anyone help me out.. I have referred many Stackoverflows solutions , but none helped me out I changed the settings of .ebextensions config file and many other options But could not get solutions. -
only OPTIONS request is sent with a 200 response
My situation is a bit similar to this question but it differs a bit nor there is an answer. My backend is python and front-end is Angular. Live sever is Ngnix/Unix while dev is Windows. Every request just sends OPTIONS request, with successful response of 200 but then GET/POST are not followed. It was working perfectly fine and only on production sever is it not working. There are no CORS errors in the console and backend is debug= True for checking purposes but not problems so far cos obviously no get/post is being made. On development machine, all is working. Previous team had added a custom header 'language': const clonedRequest = req.clone({ headers: req.headers.set('Language', lang) }); which I noticed is never sent when connected to the live one. In the development setup, I see the following headers: Accept application/json Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Connection keep-alive Content-Length 21 Content-Type application/json Host 127.0.0.1:9000 Language en Origin http://localhost:4800 Referer http://localhost:4800/start/forgot-pwd When connecting to the production from front end (Development or in production), the Language header is not being sent but I doubt it has issues. Regardless, my CORS on the backend looks like this: CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', … -
fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/main/x86_64/APKINDEX.tar.gz always fails
I am behind proxy and I have set the proxy config for Docker and able to dowload docker images but I am unable to Build from my docker file as it always fails at fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/main/x86_64/APKINDEX.tar.gz I have tried other ways like changing the repo but still am unable to build FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 #RUN sed -i 's/http\:\/\/dl-cdn.alpinelinux.org/https\:\/\/alpine.global.ssl.fastly.net/g' /etc/apk/repositories RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI dependencies && apk add libffi-dev py-cffi \ # Translations dependencies && apk add gettext \ # https://docs.djangoproject.com/en/dev/ref/django-admin/#dbshell && apk add postgresql-client # Requirements are installed here to ensure they will be cached. COPY ./requirements /requirements RUN pip install -r /requirements/local.txt COPY ./compose/production/django/entrypoint /entrypoint RUN sed -i 's/\r//' /entrypoint RUN chmod +x /entrypoint COPY ./compose/local/django/start /start RUN sed -i 's/\r//' /start RUN chmod +x /start COPY ./compose/local/django/celery/worker/start /start-celeryworker RUN sed -i 's/\r//' /start-celeryworker RUN chmod +x /start-celeryworker COPY ./compose/local/django/celery/beat/start /start-celerybeat RUN sed -i 's/\r//' /start-celerybeat RUN chmod +x /start-celerybeat COPY ./compose/local/django/celery/flower/start /start-flower RUN sed -i 's/\r//' /start-flower RUN chmod +x /start-flower WORKDIR … -
Django Rest Framework User Model Serializer Nested
I am having some issues with my DRF Serializers. I essentially have a model that has Django users as Foreign keys so I can see who is attached to a job. When I try and resolve these user ID's nested inside my Job serializer using a User serializer I only see the ID, but when I use the User serializer on it's own not nested I get the correct fields returned. Below is my code snippets. Any help would be great. models.py from profiles.models import UserProfile class Job(models.Model): name = models.CharField(max_length=256, blank=False) designer_one = models.ForeignKey(UserProfile, related_name='designer_one', on_delete=models.DO_NOTHING) designer_two = models.ForeignKey(UserProfile, related_name='designer_two', on_delete=models.DO_NOTHING) def __str__(self): return self.name class Meta(object): verbose_name = "Job" verbose_name_plural = "Jobs" ordering = ['name'] serializers.py from django.contrib.auth.models import User class UsersSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'first_name', 'last_name') class JobsSerializer(serializers.ModelSerializer): tasks = TasksSerializer(many=True, read_only=True) designer_one = UsersSerializer(many=False, read_only=True) designer_two = UsersSerializer(many=False, read_only=True) class Meta: model = Job fields = ('id', 'name', 'designer_one', 'designer_two', 'tasks') What I get returned from UsersSerializer API View [ { "id": 1, "email": "test@example.co.uk", "first_name": "Admin", "last_name": "User" }, { "id": 2, "email": "test1@example.co.uk", "first_name": "", "last_name": "" } ] What I get returned from JobsSerializer API View { … -
Django Formset Validation - Sum Values in Formset
I have a page containing a Django form, then below it a formset (dynamic number of rows). In the top form is a "total length" field, and each row of the formset below contains a "length" field. I need to validate that the sum of the lengths submitted for each row of the formset is <= the "total length" field on the single form at the top. I don't think I can do this using the normal form clean method on the form that makes up the formset, since that has no scope to get the values from the other forms in the formset. I guess I could do it in the view instead, but I'm not sure how to sum the values from the formset. Also how can I add a validation failure message (the standard Django one is fine) to the "total length" field in the single (top) form from the view? -
Counting django fields when value is True and displaying this count
I have a model in Django with Projects and Tasks. A project can have many tasks, here are my models: class Project(models.Model): project_name = models.CharField(max_length=200) is_complete = models.BooleanField(default=False) def __str__(self): return self.project_name class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) task_name = models.CharField(max_length=100) task_desc = models.TextField(max_length=600) due_date = models.DateField('due date') is_complete = models.BooleanField(default=False) task_desc.short_description = "Task description" def __str__(self): return self.task_name I would like to show a count of total tasks and total completed tasks next to the projects. I have added the below to my admin.py to show a count of total tasks per projects: def project_task_count(self, obj): return obj.task_set.count() How could I also add a count of only completed tasks to the admin, and also replicate this approach to show these counts on the website, not just in the admin panel? I have tried adding this to my model, but it dosn't work: def num_complete(self, obj): return self.is_complete.count()