Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form submission not updated when back to previous page using browser back button
I have a 2 pages, 1 page with things to display such as name and bio. Another page with form to change the name and bio. So I have submit the form and it is successful but when back button are clicked the name and bio are not updated until I refresh the page. How do I achieve so that the name and bio are updated instantly after form submission success. I know about the back button automatically reload but I don't want that approach. How to get the form submission to be updated so when I click back button the info are updated without refreshing the pages ? -
Was wondering why iterating through a dictionary using .keys in django would not work?
I know that .items would be useful to grab the value, but wanted to see why this would not work? Data: ... city_data = { 'city': json_data['name'], 'country': json_data['sys']['country'], 'temp': json_data['main']['temp'], 'feels_like': json_data['main']['feels_like'], 'temp_max': json_data['main']['temp_max'], 'temp_min': json_data['main']['temp_min'] } return render(request, ..., context={'city_data':city_data}) template: ... {% for key in city_data.keys %} <li>{{city_data.key}}</li> {% endfor %} ... -
Django - Class Based View - Restrict Access to Views based on User or Group Permissions - UserPassesTestMixin
My project is running Django 3.05 and was set up with Django cookiecutter, and the custom user model that it creates. AUTH_USER_MODEL = "users.User" I have a set of Class Based Views where I want to restrict access based on group or user permissions. I do not want to use the PermissionRequiredMixin and redirect to a 403 page. Instead, if a user does not have correct permissions I would simply like to redirect to the referring page, and display a "permission denied" banner message at the top (see screen shot below). The problem is that these permissions are not working as expected when implemented my Views. I am able to use either the admin panel or the django shell to assign permissions. For example here is the permissions as they show up in the shell: In [7]: from django.contrib.auth import get_user_model In [8]: User = get_user_model() In [9]: user = User.objects.get(id=8) In [10]: permission = Permission.objects.get(name='can run batch actions') In [11]: user.user_permissions.add(permission) In [12]: from django.contrib.auth.models import Permission ...: from django.contrib.auth.models import User In [13]: group_permissions = Permission.objects.filter(group__user=user) In [14]: group_permissions Out[14]: <QuerySet [<Permission: slatedoc | slate doc | Can add slate doc>, <Permission: slatedoc | slate doc | can … -
Why isn't my JavaScript code being executed in the order it was written [duplicate]
I am working on a dating web app using Django. One of the tabs of the app displays profiles of possible dating candidates, one profile at a time. When the user clicks on the like button on one of the profiles, a post request is sent to the server using fetch, the like is added to the database and the code checks whether there is a match or not between the user and the person (python). In case there is a match, I want to hide the person's profile and display a div with a message acknowledging the match (JavaScript). The idea is for this message to be displayed for a few seconds and then the page would refresh and move on to the next profile. My code is not executing correctly. After clicking on the like button, the person's profile displays for a few seconds and then I can see the message for a split of second and the page moves on to the next profile. How can I make this code execute according to my requirements? This is the code: function wait(ms){ var start = new Date().getTime(); var end = start; while(end < start + ms) { end … -
How to check if all modelForm data are empty?
I have created a view that renders multiple related forms together, and all of them are submitted by a single submit button to create a single parent instance with all its related forms with it. Here is a simplified example from my model classes: class Parent(models.Model): name = models.CharField(max_length=100) child1 = models.ForeignKey(Child1, blank=True, null=True, on_delete=CASCADE) class Child1(models.Model): name = models.CharField(max_length=100, blank=True) As you can see, my foreign key child1 could be null. I have also created a modelForm for each model. My view renders a Parent form and a Child1 form. Question: On POST request, I got all my POST data and pass them to my forms, so a Child1 instance is created weather its fields are empty or not, then it got attached to the Parent instance. This is not the behavior that I need. The required behavior: If all the fields in my Child1 form is empty, ignore it and don't create an instance of it, and subsequently don't attach it to the Parent instance. How can I achieve this? -
AWS media forbidden
I get the 403 error when my Heroku app tries to access pictures from my AWS bucket. I followed the Heroku guide on user uploads with Python: https://devcenter.heroku.com/articles/s3-upload-python and changed it a little so it would only affect user uploads and not my static files. Even though I turned off "block all public access" it is still forbidden My settings: AWS_ACCESS_KEY_ID = os.environ.get('my key') AWS_SECRET_ACCESS_KEY = os.environ.get('my secret key') AWS_STORAGE_BUCKET_NAME = 'my bucket name' #STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' #DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' if DEBUG == False: MEDIA_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.eu-west-1.amazonaws.com/' # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' AWS_QUERYSTRING_AUTH = False and here is my CORS: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD", "POST", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] but it is copied and pasted directly from Heroku's guide so I doubt it is the problem. -
How can I use NPM modules with Django inside an app?
I have a Django project with 2 apps. I want to use the Notion API in one of the apps, so I have to install it's NPM module. However, I have never use NPM nor a bundler (I understand I have to use one for the import statement). I have no idea on how to do it, where should I install the module? Should I install Webpack or something similar? How can I integrate both of this technologies with Django? Can someone please explain this to me, or reffer to an article/video explaining? I have been trying for hours now and I can't find anything detailed. I have checked the following links: Django how to use npm modules with static/ templates https://gist.github.com/brizandrew/685a588fbefbd64cd95ed9ec4db84848 https://www.saaspegasus.com/guides/modern-javascript-for-django-developers/integrating-javascript-pipeline/ https://www.saaspegasus.com/guides/modern-javascript-for-django-developers/integrating-javascript-pipeline/ https://www.techiediaries.com/django-webpack-react/ https://owais.lone.pw/blog/webpack-plus-reactjs-and-django/ https://pythonrepo.com/repo/owais-django-webpack-loader-python-developing-restful-apis And a lot more. They either don't have what I need (they are for react), or I can just not understand them. I know there are probably a lot of articles on this, but either I just can't find them, or they are too complicated for me (sorry I'm dumb). If anyone can help me, it would make my day. Thanks! -
Django REST - hide deserialized data
I would like to store some data in one of my database field. The data is added to that field while deserialization with POST method. Later when I want to show data with GET method I don't want that one field to be presented. When I do POST I deserialize that string: { "car_id": 3, "rating": 3 } Later in views.py I do the deserialization while POST: @api_view(['POST']) def car_rate(request): if request.method == 'POST': rate_data = JSONParser().parse(request) rate_serializer = CarRateSerializer(data=rate_data) if rate_serializer.is_valid(): try: car_obj = Car.objects.get(pk=rate_data['car_id']) except Car.DoesNotExist: return JsonResponse({'message': 'The car with given ID does not exist!'}, status=status.HTTP_404_NOT_FOUND) # check if rate is from 1 to 5 r = rate_serializer.validated_data['rating'] if int(r) >= 1 and int(r) <= 5: rate_serializer.save() return JsonResponse({'message':'The rate is in the scope!'}) else: return JsonResponse({'message':'The rate is NOT in the scope!'}) return JsonResponse(rate_serializer.errors) And there is my models.py: class Car(models.Model): make = models.CharField(max_length=15) model = models.CharField(max_length=15) avg_rating = models.FloatField(default=0) def __str__(self): # print it when Car instance is needed return self.make class CarRate(models.Model): car_id = models.ForeignKey(Car, related_name='rates', on_delete=models.CASCADE, default=0) rating = models.PositiveIntegerField(default=0) The code does works (somehow). For now there can be added rates for one car (multiple rates) with POST moethods. I store the … -
Setting a CSS variable in Django
I am creating custom user pages where they are able to change basic features like the font, color, or background color of different link boxes. Currently, I am passing the saved variables from the database to the HTML template but I was wondering if I could pass them into the external CSS style sheet. I am having to do inline CSS styling inside the HTML template. I'd like the link hover effect to stay but whenever I set the background color of the link via inline CSS in my HTML template it will break the hover effect. Note: Only including part of my index.html file index.html {% load static %} <link rel="stylesheet" type="text/css" href="{%static 'css/style.css' %}"/> <div id="links"> <a class="link" style="color:{{ linkcolor }}; background-color:{{ linkbc }}; font-family:{{ linkfont }};" href="https://www.instagram.com" target="_blank"><Instagram</a> style.css #links { max-width: 500px; width: auto; display: block; margin: 20px auto; } .link { display: block; box-shadow: 10px 10px black; text-align: center; margin-bottom: 20px; padding: 17px; text-decoration: none; font-size: 1.4rem; font-weight: 300; transition: all .25s cubic-bezier(.08, .59, .29, .99); border-radius: 10px; } .link:hover { background-color: rgba(255, 255, 255, 0.3); color: #000000; border: none; } views.py def index(request): editor = cssEditor.objects.get(pk=1) return render( request, "SocialLinks/index.html", { "linkcolor":editor.link_color, "linkfont":editor.link_font, "linkbc":editor.link_bc … -
Quickly check existence of a Many-To-Many relationship without too many queries in Django
On my old system, The apps installed for each website would look like this (if they had been in Django): class Website(models.Model): name = models.CharField(max_length=255) ... class Apps(models.Model): website = models.ForeignKey(Website, on_delete=models.CASCADE) blog = models.BooleanField(default=False) shop = models.BooleanField(default=False) ... # To see if the shop app is installed, you can easily do this from a `Website` instance loaded previously in the code website = Website.objects.get(pk=1) ... if website.apps.shop: pass It's nice because you can quickly check if an app is installed, however it feels wrong as you need a separate apps table where every app detail is, and that table is not linked to websites. So the other solution, which follows conventions and best practices I think, is to have a Many-To-Many relationship like this: class App(models.Model): name = models.CharField(max_length=255) ... class Website(models.Model): name = models.CharField(max_length=255) apps = models.ManyToManyField(App) ... # To see if the shop is installed, would I need to do this every time from a `Website` instance: if website.apps.filter(name="shop").exists(): pass I like the latter as it feels cleaner and the App table can have more columns to hold details about each app. However the check to see if an app is installed is quite long and tedious, … -
How to save file in the file system and its path in the database using Python?
I want to save file to the file system, currently I am working with django and it provides a pretty neat way of doing this: models.py class Report(models.Model): name = models.CharField(max_length=120) image = models.ImageField(upload_to = 'charts', blank=True, null=True) remarks = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(Profile, on_delete=models.PROTECT) utils.py (this file is created by me): import base64, uuid from django.core.files.base import ContentFile def get_report_image(data): f, str_img = data.split(';base64, ') decoded_img = base64.b64decode(str_img) img_name = str(uuid.uuid4())[:12] + '.png' data = ContentFile(decoded_img, name=img_name) return data And to save this data to the data base I use django orm Report.object.create(name="report name", remarks='Report Remarks', author=request.user.id, image=get_report_image(base64_encoded_image)) But I want to do the same thing without django Sorry for any mistake I made in asking the question or explaining my problem, I am a beginner -
Split Model declaration among several app in Django
I am working and building my website with Django and I am facing this logical issue. My project is made by several app. I would like to declare in each one of these a "piece" of a bigger model that will be represented in one single table- Example: model Person model DetailsPerson As each single app specifies a specific part of the person, my idea was to decentralize the declaration of DetailsPerson model so that they figure in one single table but each app enlarge the fields the app needs to work. Is this possible? -
Windows Deploying Django
https://realpython.com/django-hosting-on-heroku/#step-7-deploy-your-django-project-to-heroku Following this I am running into an issue with deploying Django with Python using Windows. It seems that it can't find the Procfile even though it's inside the folder. (portfolio) C:\Users\arund\Desktop\Code\Django\portfolio-project>heroku local [WARN] Cannot read property '1' of null [FAIL] No Procfile and no package.json file found in Current Directory - See run --help TypeError: Cannot convert undefined or null to object at Function.keys (<anonymous>) at Index.run (C:/Users/arund/AppData/Local/heroku/client/7.59.2/node_modules/@heroku-cli/plugin-local/lib/commands/local/index.js:30:38) at Index._run (C:/Users/arund/AppData/Local/heroku/client/7.59.2/node_modules/@oclif/command/lib/command.js:44:31) (portfolio) C:\Users\arund\Desktop\Code\Django\portfolio-project> After I ran $ echo "web: python manage.py runserver 0.0.0.0:\$PORT" > Procfile $ git add Procfile $ git commit -m "Specify the command to run your project" -
HTML can't load image on page
in the following html, i want to load and image but as the you can see below the image has been send but not displayed. Any ideas? maybe problem with css? (I am using materiallized css) <html> {% extends "main/header.html" %} {% load static %} {% block content %} <img class="responsive-img" src="{% static 'images/MOA_LOGO_p.jpg' %}" alt="logo" > {% endblock %} -
Django Application Wont Load User Uploaded Image
I used Django Admin to upload an image and I am trying to get it to display in a template. The alt text is displayed but I keep getting a 404 error for the image and it does not display. When I uploaded the image the path that it pulls in the template media/images/mari-profile-pic.png is valid and contains the image I am trying to display. models.py from django.db import models # Create your models here. class Image(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='images/') views.py from django.shortcuts import render from django.http import HttpResponse from .models import Image # Create your views here. def index(request): imageModel = Image.objects.get(pk=1) return render( request, "SocialLinks/index.html", { "profile_pic_title":imageModel.title, "profile_pic":imageModel.image } ) index.html template <div id="profile"> <img id="userPhoto" src="{% get_media_prefix %}{{ profile_pic }}" alt="{{ profile_pic_title }}"> </div> settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I have tried removing and adding the {% get_media_prefix %} tag and the image still does not display. -
django-channels: no route found for path
I've been following this tutorial on django-channels: https://youtu.be/RVH05S1qab8 I followed every step that's in the video, first when i encountered the issue, i rewatched it and followed along once again to make sure i did everything correctly, but that wasn't it. i'm fairly new to django so i'm sorry if my explanation is imprecise i set up the websocket in the thread.html file: <script> // websocket scripts var loc = window.location var wsStart = 'ws://' if(loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) socket.onmessage = function(e){ console.log('message', e) } socket.onopen = function(e){ console.log('open', e) } socket.onerror = function(e){ console.log('error', e) } socket.onclose = function(e){ console.log('close', e) } </script> my consumers.py file: import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) async def websocket_disconnect(self, event): print('disconnected', event) async def websocket_receive(self, event): print('receive', event) and routing.py: from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator from chat.consumers import ChatConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^messages/(?P<username>[\w.@+-]+)/$", ChatConsumer), ] ) … -
Problem with validation. Choose the correct option. Your option is not among the valid values
I'm begginer in Python and Django. I'm trying to write simple Property management System. I've got problem with asigning existing house association to new property entry. My files: models.py class Property(models.Model): # Fields id = models.AutoField(primary_key=True) name = models.CharField(max_length=45, blank=False) # Property name address = models.CharField(max_length=198, blank=False) # Property address postalcode = models.CharField(max_length=6, blank=False) # Property postalcode city = models.CharField(max_length=45, blank=False) # Property city kw_number = models.CharField(max_length=15, blank=True) # Numer KW ha_choice = models.CharField(max_length=2, choices=[(i.pk, i.name) for i in HousingAssociation.objects.all()]) # Foreign Keys # TODO zmiana on_delete na inny! house_association = models.ForeignKey(HousingAssociation, on_delete=models.CASCADE) # Metadata class Meta: ordering = ['id'] # Methods def add(self): self.save() def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" # return self.id, self.name, self.address, self.postalcode, self.city, self.kw_number return self.name forms.py class PropertyForm(forms.ModelForm): class Meta: model = Property fields = ('name', 'address', 'postalcode', 'city', 'ha_choice', 'kw_number') views.py def property_form_new(request): if request.method == "POST": form = PropertyForm(request.POST) if form.is_valid(): form.save() return render(request, 'registration/prop/success.html') else: form = PropertyForm() return render(request, 'registration/prop/prop_new.html', {'property_new': form}) In case of that django returns to me this: screenshot It means 'Choose the correct option. 14 is not among the valid values.' 14 is an id of existing entry in db … -
Why does python give FileNotFoundError: [Errno 2] No such file or directory error even though the file exists?
I am trying to make a machine learning model and use django rest framework to connect it. My folder structure is like this server | +-- chat | | | +-- DistilBertModel | | | | | +-- OurModel | | | | | | | +-- BERT_model.py | | | +-- chatbot.py | | | +-- chatbot_predict.py | | | +-- model.sav | | +-- data | | | | | | | +-- test_chatbot.csv | | | +-- answers.json | +-- migrations | +-- __init__.py | +-- admin.py | +-- apps.py | +-- models.py | +-- serializers.py | +-- tests.py | +-- urls.py | +-- views.py +-- core | +-- templates | +-- db.sqlite3 | +-- manage.py | +-- requirements.txt In chatbot_predict.py file I am trying to load the model and get a prediction using that model. The code is like this import joblib loaded_model = joblib.load ('model.sav') def get_prediction (message, loaded_model = loaded_model): return prediction When I run this file using python chatbot_predict.py using command line it works fine. However when I import this get_prediction function in server/chat/views.py and run python manage.py runserver it gives the error What am I doing wrong to get that FileNotFoundError ? -
share variable between SerializerMethodField methods
First of all, I would like to mention that I read this question but it doesn't really answer mine. I would like to "share" a variable between two SerializerMethodField methods to avoid computing it twice. My first idea would have been to do something similar to this: an additional attribute which I only set if the value is None. However, Django doesn't allow to add attributes which are not present in Meta.fields # code modified to include only what's important for this question class MySerializer(serializers.ModelSerializer): a = serializers.SerializerMethodField() b = serializers.SerializerMethodField() sum = None def compute_sum(self, id): if self.sum is None: self.sum = AnotherModel.objects.all().aggregate(Sum('amount'))['amount__sum'] return self.sum def get_a(self, obj): return self.compute_sum(obj.id) def get_b(self, obj): return self.compute_sum(obj.id) / 100 >= obj.target class Meta: model = MySuperModel fields = ['asdf', 'a', 'b'] Furthermore, I feel like there is probably a way easier way to accomplish this. -
PermissionRequiredMixin with django view method
I know, that we have a PermissionRequiredMixin and it has got permission_required. I have a question, how to do that with on django view method. Thank you, guys!! -
django server running Error. modul not found. can someone please tell me what exactly the problem is?
i've already added the App to my setting.py INSTALLED_APPS and also Edited my MIDDLEWARE enter image description here -
How Do I Fix An Exception Error for Django/Sendgrid?
I have a little problem sending emails via sendgrid When I send out an activation email I get the follow error back: exception ("'int' object has no attribute 'get'",) I have done some debugging and an email is being generated with a unique activation key. All the fields needed(from, recipients, subject, html email) have been filled in I have also created a new api_key on sendgrid and it has full access. I would appreciate any feedback, if you need any more information, please let me know. below is the code I'm using: View.py: class AccountEmailActivateView(FormMixin, View): success_url = '/' form_class = ReactivateEmailForm key = None def get(self, request, key=None, *args, **kwargs): self.key = key if key is not None: qs = EmailActivation.objects.filter(key__iexact=key) confirm_qs = qs.confirmable() if confirm_qs.count() == 1: obj = confirm_qs.first() obj.activate() messages.success(request, "your email has been confirmed, please login.") return redirect("account:login") else: activated_qs = qs.filter(activated=True) if activated_qs.exists(): reset_link = reverse("password_reset") msg = """Your email has already been confirmed Do you need to <a href="{link}">reset your password?</a> """.format(link=reset_link) messages.success(request, mark_safe(msg)) return redirect("account:login") context = { 'form': self.get_form(), 'key': key, } return render(request, 'registration/activation-error.html', context) def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) … -
Sending data from import button directly to database
What i need to do is to import a txt file from the html: <form method="post" enctype="multipart/form-data" action="/import_csv/"> {% csrf_token %} <input type="file" name="document" class="btn btn-sm btn-primary shadow-sm"/> <input type="submit" class="btn btn-md btn-primary shadow-sm mr-1"></input> </form> I tried also using button with an onclick event, but got the same error so i converted into input tag. The action on the form tag is the name of the function in the view.py, that does the following: def import_csv(request): context = {} # data from the txt files if request.method == 'POST': my_file = request.FILES['document'] txtData = my_file.read() html = txtData.decode('utf-8') df = pd.read_csv(html, delimiter='\t+|\t\t', header=1) print(df) df.rename(columns={'Type d’enregistrement': 'Type', 'Historique du taux de glucose (mg/dL)': 'GlucoseHistorique'}, inplace=True) df.drop('Taux de glucose scanné (mg/dL)', inplace=True, axis=1) df.drop('Insuline à action rapide (sans valeur numérique)', inplace=True, axis=1) df.drop('Insuline à action rapide (unités)', inplace=True, axis=1) df.drop('Nourriture (sans valeur numérique)', inplace=True, axis=1) df.drop('Glucides (grammes)', inplace=True, axis=1) df.drop('Insuline à action lente (sans valeur numérique)', inplace=True, axis=1) df.drop('Insuline à action lente (unités)', inplace=True, axis=1) df.drop('Commentaires', inplace=True, axis=1) df.drop('Glycémie avec électrode de dosage (mg/dL)', inplace=True, axis=1) df.drop('Cétonémie (mmol/L)', inplace=True, axis=1) df.drop('Insuline repas (unités)', inplace=True, axis=1) df.drop('Insuline de correction (unités)', inplace=True, axis=1) df.drop('Insuline modifiée par l’utilisateur (unités)', inplace=True, axis=1) df.drop('Heure précédente', … -
django sort export csv by date most recent first
I'm a beginner in django, I'm trying to sort my csv by date In my view. I can export my schedules in csv and display them in my view but I don’t know how to sort them by date by the most recent one. But in My view not in my directory. In my template it's Like this : export_21_11_2021-151707.csv export_22_11_2021-151707.csv export_23_11_2021-151707.csv But I want to sort by date the most recent like this : export_23_11_2021-151707.csv export_22_11_2021-151707.csv export_21_11_2021-151707.csv My fonction export def vm_schedule_export(): timestr = time.strftime("%d_%m_%Y-%H%M%S") schedules = VmSchedule.objects.all().values('schedule', 'action', 'dow', 'dom', 'mon', 'h', 'm', 'pause', 'vms__name') media_url = settings.MEDIA_ROOT if not os.path.exists(f'{media_url}appli'): os.makedirs(f'{media_url}appli') if not os.path.exists(f'{media_url}appli/vm'): os.makedirs(f'{media_url}appli/vm') if not os.path.exists(f'{media_url}' f'appli/vm/schedule_export'): os.makedirs(f'{media_url}appli/vm/schedule_export') with open( f'{media_url}appli/vm/schedule_export/export_' + timestr + '.csv', mode='w', encoding='utf8') as csv_file: fieldnames = ['nom', 'action', 'dow', 'dom', 'mon', 'h', 'm', 'pause', 'vms'] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() for k in range(schedules.count()): writer.writerow({'nom': schedules[k]["schedule"], 'action': schedules[k]["action"], 'dow': schedules[k]["dow"], 'dom': schedules[k]["dom"], 'mon': schedules[k]["mon"], 'h': schedules[k]["h"], 'm': schedules[k]["m"], 'pause': schedules[k]["pause"], 'vms': smart_str(schedules[k]["vms__name"])}) and where I show all export : def vm_schedule_download(request): media_url = settings.MEDIA_ROOT if not os.path.exists(f'{media_url}appli'): os.makedirs(f'{media_url}appli') if not os.path.exists(f'{media_url}appli/vm'): os.makedirs(f'{media_url}appli/vm') if not os.path.exists(f'{media_url}' f'appli/vm/schedule_export'): os.makedirs(f'{media_url}appli/vm/schedule_export') filenames = os.listdir(f'{media_url}appli/vm/schedule_export') return render(request, 'appli/vm/vm_schedule_download.html', {'filenames': filenames}) My template : {% for … -
How to count items containing specific value in Django Many to Many relationship
I have a django application used for annotation where i save information regarding image annotations into the model BiomarkerAnnotations through a many-to-many relationship. I keep track of which users have annotated the images with the annotated field. from django.contrib.auth.models import User class Biomarker(models.Model): name = models.CharField(max_length=256) description = models.CharField(max_length=1024) class Image(models.Model): number = models.IntegerField(default=0) absolute_path = models.CharField(max_length=2560) biomarkers = models.ManyToManyField(Biomarker, through='BiomarkerAnnotations', related_name="biomarker_annotations") annotated = models.ManyToManyField(User, related_name="annotated_by") class BiomarkerAnnotations(models.Model): _image = models.ForeignKey(Image, on_delete=models.CASCADE) biomarker = models.ForeignKey(Biomarker, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True,on_delete=models.SET_DEFAULT, default=1) I would like to create a view that returns, for a specific user (the one sending the request), how many images he has annotated and how many are left to annotate. So far I've reached this point, but it doesn't seem to work: the total count returned by the query is bigger than the images count. class AnnotStatsSerializer(serializers.ModelSerializer): annotations = serializers.IntegerField() count = serializers.IntegerField() class Meta: model = Image fields = ("count", "annotations") class AnnotatedStatsViewSet(viewsets.ReadOnlyModelViewSet): queryset = Image.objects.all() serializer_class = AnnotStatsSerializer def get_queryset(self): queryset = self.queryset user_object = self.request.user project_id = self.request.query_params.get('project', None) if project_id is None: raise Http404 queryset = queryset.annotate(annotations=Case(When(annotated__id__exact=user_object.id, then=Value(1)), default=Value(0), output_field=IntegerField())) \ .values('annotations').annotate(count=Count('annotations')).order_by('annotations') \ .values('count', 'annotations') return queryset Any help appreciated.