Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ReadOnly on serializers.py
In this piece of code, in RegUpdate() field 'rooms' should be ReadOnly from rest_framework import serializers from .models import Registration class RegSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'rooms', 'first_name', 'last_name', 'admin', 'pasport_serial_num', 'birth_date', 'img', 'visit_date', 'leave_date', 'guest_count', 'room_bool', 'price') model = Registration class RegUpdater(serializers.ModelSerializer): class Meta: fields = ('id', 'rooms', 'leave_date', 'room_bool') #rooms should be ReadOnly model = Registration -
Pagination on searched data in DJANGO using AJAX call
Iam implementing pagination on searched data. When click on the next button it should display the next 5 sets of records and when click on the previous button it should display the previous 5 sets of records using ajax call.Now my doubt is that how to sent searched value and page number along with data?? read_data.html <!DOCTYPE html> {% load static %} <h3>User List</h3> <div class="card-body" > {% if word %} {% for words in word %} <table class="table table-bordered" style="width:85%;margin-right:auto;margin-left:auto;" id="exa" > <thead class="table-success"> {% endfor %} <tr> <th scope="col">Id</th> <th scope="col">Username</th> <th scope="col">Name</th> <th scope="col">Admin</th> <th scope="col">User</th> <th scope="col">Status</th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> {% for words in word %} <tbody> <tr> <th>{{words.id}}</th> <th>{{words.username}}</th> <th>{{words.first_name}}</th> <th>{{words.is_superuser}}</th> <th>{{words.is_staff}}</th> <th>{{words.is_active}}</th> <th><a href="/update_user/{{words.id}}" class="btn btn-success" name="{{words.id}}" onclick="loadDiv3({{words.id}})">Update</a></th> <th><a href="/password_reset/{{words.id}}" class="btn btn-success" name="{{words.id}}" onclick="loadDiv2({{words.id}})">Reset Password</a></th> </tr> {% endfor %} </tbody> </table> <ul class="pagination"> {% if word.has_previous %} <li class="page-item"> <a href="?page={{word.previous_page_number}}&results={{query}}" class="page-link" onclick="loadDiv9({{page}})" id="previous"><<< Previous</center></a> </li> {% endif %} {% if word.has_next %} <li class="page-item"> <a href="?page={{word.next_page_number}}&results={{query}}" class="page-link" id="next">Next >>></a> </li> {% endif %} </ul> {% else %} <p>no records available</p> {% endif %} <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script type="text/javascript" src="{% static 'js/pagination.js' %}"></script> pagination.js $("#next").on('click',function(){ event.preventDefault(); var results=$('#results').val(); var page=$('#page_number').val(); … -
Social Network Login Failure with microsoft graph django allauth
I am trying to log in with outlook it gives an enter image description hereerror -
what should i do to be able to post multiple contents in my code in django rest framework?
This is my serializers.py: from rest_framework import serializers from .models import product class productSerializer(serializers.ModelSerializer): class Meta: model= product fields="__all__" views.py: from django.shortcuts import render from .models import * from rest_framework import viewsets from .serializers import productSerializer from rest_framework.parsers import JSONParser class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class=productSerializer When i want to post multiple contents like this: [ { "Number": 1, "name": "1005001697316642", "image": "https://", "description": "fffffffff", "price": "USD 23.43", "buy": "https://" }, { "Number": 2, "name": "1005002480978025", "image": "https://", "description": "dffdfdddddddddddddd", "price": "USD 0.89", "buy": "https://" } ] I get this error: HTTP 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } what should i do to be able to post multiple contents? -
host "localhost" (::1) and accepting TCP/IP connections on port 5432?
I'm trying to set up a Django website that connects to the "default" PostgreSQL db, all within Docker. Note, I'm trying to db inside the postgres image. After running the docker-compose up --remove-orphans command, the error within the title is executed. Can I do anything to fix this? What I am currently using is: Settings.py - DATABASES DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': 5432, } } Dockerfile FROM python:3.7-slim as production ENV PYTHONUNBEFFERED=1 WORKDIR /app/ RUN apt-get update && \ apt-get install -y \ bash \ build-essential \ gcc \ libffi-dev \ musl-dev \ openssl \ postgresql \ libpq-dev COPY requirements/prod.txt ./requirements/prod.txt RUN pip install -r ./requirements/prod.txt COPY manage.py ./manage.py COPY website ./website EXPOSE 8000 FROM production as development COPY requirements/dev.txt ./requirements/dev.txt RUN pip install -r ./requirements/dev.txt COPY . . docker-compose.yml version: "3.7" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres services: website: image: "django_image:latest" command: python manage.py runserver 0.0.0.0:8000 volumes: *service-volumes environment: *app-variables depends_on: - db_migrate ports: - "8000:8000" db_migrate: image: "django_image:latest" command: python manage.py migrate volumes: *service-volumes environment: *app-variables depends_on: - postgres postgres: image: "postgres:latest" ports: - "5432:5432" … -
Django / Sending email with Mail Service Prodiver like Mailjet
I have installed django-anymail My SPF and DKIM are configured in my ISP Here is my settings.py : EMAIL_BACKEND = "anymail.backends.mailjet.EmailBackend" ANYMAIL = { "MAILJET_API_KEY": os.getenv('MYAPP_MAILJET_API_KEY'), "MAILJET_SECRET_KEY": os.getenv('MYAPP_MAILJET_API_SECRET'), } EMAIL_HOST = 'in-v3.mailjet.com' EMAIL_HOST_USER = '????' EMAIL_HOST_PASSWORD = '????' EMAIL_HOST_PORT = 587 Views.py send_mail('contact form','click',mail1,[mail2],fail_silently=False) I got confused for EMAIL_HOST_USER and EMAIL_HOST_PASSWORD As I want to use mailjet, is it necessary ? Also is send_mail the right function in this case ? -
How to simulate user intercation in Django?
I have a Django project representing an abstract retail store. Let's say it's deployed on a server and is available in the local network. I want to write another program (or extend this one?) to generate a bunch of Users, automate the process of signing up and logging in and automate their interaction with the system: make them interact with the system to order goods. So it's not just unit testing of my system but rather demonstration of how it works in real life. And I want to spawn many users to see how my system can handle many requests at once. Is there some kind of framework for that? How would you implement this? Thanks. -
Make thumbnail after ImageField save
I want to make thumbnail of an uploaded image after the Imagefield model is saved. At this moment i'm getting raise Exception error: Could not create thumbnail - is the file type valid?". Can you guys help me how to get it working? models.py from django.contrib.auth.models import User from django.db import models from PIL import Image as Img class Image(models.Model): img_owner = models.ForeignKey(User, on_delete=models.CASCADE, default=User) image = models.ImageField(null=True, blank=False) thumbnail = models.ImageField(upload_to="thumbs", editable=False) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-date_added"] def save(self, *args, **kwargs): if not self.make_thumbnail(): # set to a default thumbnail raise Exception("Could not create thumbnail - is the file type valid?") super(Image, self).save(*args, **kwargs) def make_thumbnail(self): size = 128, 128 im = Img.open(self.image) im.thumbnail(size) im.save(self.image.name + ".thumbnail", "PNG") seralizers.py from rest_framework import serializers from .models import Image class ImageSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source="img_owner.username") thumbnail = serializers.ReadOnlyField() class Meta: model = Image fields = ["url", "author", "img_owner", "image", "thumbnail", "date_added"] views.py from rest_framework import permissions, viewsets from .models import Image from .serializers import ImageSerializer class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer permission_classes = [permissions.IsAuthenticated] """ Bellow definition overrides queryset and filter images by loged user. """ def get_queryset(self): user = self.request.user return Image.objects.filter(img_owner=user) -
Reduce time for Loop over multiple objects to get value Django
I have a Dataframe in which a column Code is increased significantly everyday and these codes are to be converted into object description for which I am doing something like the following: product = [] beacon = [] count = [] c_start = time.time() for i, v in df["D Code"].iteritems(): product.append(Product.objects.get(short_code=v[:2]).description) #how to optimize this? beacon.append("RFID") count.append(v[-5:]) c_end = time.time() print("D Code loop time ", c_end-c_start) Now initially when the rows were less it used to work in no time but as the data increased the combined Database call for every code takes too much time. Is there any more efficient Django method to loop over a list and get the value? The df['D Code]` looks something like this: ['TRRFF.1T22AD0029', 'TRRFF.1T22AD0041', 'TRRFF.1T22AD0009', 'TRRFF.1T22AD0032', 'TRRFF.1T22AD0028', 'TRRFF.1T22AD0026', 'TRRFF.1T22AD0040', 'HTRFF.1T22AD0003', 'TRRFF.1T22AD0048', 'PPRFP.1T22AD0017', 'TRRFF.1T22AD0047', 'TRRFF.1T22AD0005', 'TRRFF.1T22AD0033', 'TRRFF.1T22AD0024', 'TRRFF.1T22AD0042'], -
Looping through a nested JSON object format in datatables
I'm looking to iterate through a JSON object in javascript and I also, wonder that whether my json format is correct and efficient or not. https://datatables.net/ I want to show the relationship between tables in a single table. For example, I want to get: ID hospital date type suffix description name prefix description 1 01-01-2021 cov G result Oslo S result 2 03-03-2021 cov G result Oslo S result 3 05-05-2021 cov G result Kiev S result models.py class Samples(models.Model): hospital_date = models.DateField() source_sample = models.ForeignKey(SourceSample, on_delete=models.CASCADE) projects = models.ForeignKey(Projects, on_delete=models.CASCADE) class SourceSample(models.Model): type = models.CharField(max_length=128) suffix = models.CharField(max_length=128) description = models.CharField(max_length=256) class Projects(models.Model): name = models.CharField(max_length=128) prefix = models.CharField(max_length=128) description = models.CharField(max_length=256) json "data": { "samples": { "id": "1", "hospital_date": "01-01-2021", "source_sample": { "type": "T", "suffix": "G", "description": "result" }, "project": { "name": "Valencia", "prefix": "S", "description": "result" }, } } js var table = $('#example').DataTable({ "ajax": { url: "/json", type: "GET" }, "columns": [{"data": "id"}, {"data": "hospital_date"},] Thank you for help. Best regards. -
update or delete on table "users_user" violates foreign key constraint "articles_article_users_user_id"id=5 still referenced from table "articles_arti
I am working with Django v4.* and I have linked 2 table/model Users and Articles and my aim is when user is deleted I don't want to delete the article or vice versa, so I referenced user on_delete=models.DO_NOTHING in the Article model, but I am getting this error when I tried to delete a user, it seems to my that DO_NOTHING is not working the way I thought it does?How I can pass this and achieve what I tend to do without getting constrain error? Thanks class Article(models.Model): title = models.CharField(max_length=355) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='articles') ..... -
Display integer <li> in Django
is there anyone will share me how print out integer from models.py on front page (html) with li, example <li class="nameclas">1</li><li class="nameclas">2</li><li class="nameclas">3</li> and etc. on the models of Django I write class Number and the inside numb = models.IntegerField() then in views I wrote makenumb = Number.objects.values_list('numb', flat=True).distinct() in the html I using for loop {% for i makenumb %} {% endfor %} But at the html display, the number was showing whole number, and not splitted on by <li> Regards, Thank you -
Django after adding data the size of the db.sqlite3 file has not changed
I tried to add data to db.sqlite3 of Django, but the file size has not changed. Where is my data stored? -
Maximum recursion depth exceeded while deleting in django admin
I have the following Folder model which represents all the folders I have inside a directory : class Folder(models.Model): folder_name = models.CharField(max_length=200) parent_folder = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='childrens') def __init__(self, *args, **kwargs): super(Folder, self).__init__(*args, **kwargs) if self.pk is not None: self.initial_filepath = self.filepath() def save(self, *args, **kwargs): on_creation = self.pk is None if on_creation: os.mkdir(self.filepath()) else: os.rename(self.initial_filepath, self.filepath()) super(Folder, self).save(*args, **kwargs) def delete(self, *args, **kwargs): shutil.rmtree(self.filepath(), ignore_errors=True) super(Folder, self).delete(*args, **kwargs) def filepath(self): if not self.parent_folder: return f'media/scripts/{self.folder_name}' else: return f'{self.parent_folder.filepath()}/{self.folder_name}' The problem is, when I'm in the admin page and I try to delete a folder, if it has subfolders in it (i.e. if the folder I'm deleting is the parent_folder of another folder instance) it doesn't delete any of the selected folders and returns a RecursionError after a few seconds. I've checked my code, and I don't see any recursion loop inside my own code, and I didn't manage to determine where it was coming from. I've also overriden the delete_queryset method in my admin.py but the issue doesn't seem to come from there as it still doesn't work if I try to delete my parent folder from inside the page to modify my folder. class FolderAdmin(admin.ModelAdmin): def … -
how to solve "detail": "JSON parse error - Extra data: line 8 column 3 (char 153)" error in django rest framework?
I can create a new post with this: { "Number": 1, "name": "1005001697316642", "image": "https://", "description": "fffffffff", "price": "USD 23.43", "buy": "https://" } but when i want to post multiple contents like this: { "Number": 1, "name": "1005001697316642", "image": "https://", "description": "fffffffff", "price": "USD 23.43", "buy": "https://" }, { "Number": 2, "name": "1005002480978025", "image": "https://", "description": "dffdfdddddddddddddd", "price": "USD 0.89", "buy": "https://" } i get this error: HTTP 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "JSON parse error - Extra data: line 8 column 3 (char 153)" } image How can i solve this problem? -
Django pagination throwing an error when trying to go to the next page
I'm currently working on a project that will display advertisements on a website. I'm facing some level of difficulty even after researching for half a day trying to find a solution but with no luck. I have a HomeView which inherits the ListView where I have paginate_by = 30 and this displays on the home page and works as it should in terms of going to whatever page number I click on. I have another view called NegotiableAdView which also inherits the ListView. In this view I'm getting a value from request.GET which is either yes or no then filter the queryset accordingly to return. It displays the number of ads I set the paginate_by attribute to, but the problem is whenever I click on page 2 or whatever page number it is saying for example: Page not found (404)... Invalid page (2): That page contains no results I'm not sure why it's giving that error. But do I have the following... Within the html file containing the form: <form method="GET" action="{% url 'store:search-negotiation' %}"> <div id="collapseThreee" class="panel-collapse collapse " role="tabpanel" aria-labelledby="headingThreee"> <div class="panel-body"> <div class="skin-minimal"> <ul class="list"> <li> <input type="radio" id="radio-yes" name="negotiable" value="Yes"> <label for="yes">Yes</label> </li> <li> <input type="radio" … -
Raise error if the input is False (Boolean) while uploading excel sheet via Django Form
I have a Django form through which I am uploading an excel sheet to Database, Here, some columns have boolean fields (True/False). In such fields (e.g. block_covered, village_covered etc) , I want to raise an error such as: "This field can not be false", whenever the field value is False(0), so that it only takes the value which are True(1) and ignore the user/myself to give false boolean value as input in excel sheet while uploading i.e. prevent them from uploading the sheet. The related files are as below. Model.py BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) UNIT_CATEGORIES = (('ABC', 'ABC'), ('XYZ', 'XYZ')) class GroupDetail(models.Model): unit_type = models.CharField(max_length=16, choices=UNIT_CATEGORIES) state_name = models.CharField(max_length=100) unit_name = models.CharField(max_length=100) districts_covered = models.BooleanField(verbose_name=_('Districts Covered "yes/no"'), choices=BOOL_CHOICES) block_name = models.CharField(max_length=100) block_covered = models.BooleanField(verbose_name=_('Block Covered "yes/no"'), choices=BOOL_CHOICES) village_name = models.CharField(max_length=100) village_covered = models.BooleanField(verbose_name=_('Village Covered "yes/no"'), choices=BOOL_CHOICES) number_of_group = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) number_of_farmers = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(1000)]) Form.py class add_to_database(forms.ModelForm): class Meta: model = GroupDetail fields = ["unit_type", "state_name", "unit_name", "district_name", "districts_covered ", "block_name", "block_covered", "village_name", "village_covered", "number_of_group", "number_of_farmers"] labels = { "unit_type":"Unit Type", "state_name":"State Name", "unit_name":"Unit Name", "district_name":"District Name", "districts_covered":"Districts Covered (Yes/No)", "block_name":"Block Name", "block_covered":"Block Covered (Yes/No)", "village_name":"Village Name", "village_covered":"Village Covered (Yes/No)", "number_of_group":"Number of groups", "number_of_farmers":"Number of farmers"} widgets = … -
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 1: ordinal not in range(128)
So, as title of the questions says, I have a problem with encoding/decoding of strings. I am using: python 2.7 | django 1.11 | jinja2 2.8 Basically, I am retrieving some data from data base, I serialize it, set cache on it, then get the cache, deserialize it and rendering it to the template. Problem: I have first names and last names of persons that have characters like "ă" in the names. I serialize using json.dumps. A sample of serialized dictionary looks like (I have 10 like this): active_agents = User.region_objects.get_active_agents() agents_by_commission_last_month = active_agents.values(.... "first_name", "last_name").order_by( '-total_paid_transaction_value_last_month') Then, when I set the cache I do it like: for key, value in context.items(): ...... value = json.dumps(list(value), default=str, ensure_ascii=False).encode('utf-8') , where value is the list of dictionaries returned by .values() from the aforementioned code and key is region_agents_by_commission_last_month (like the variable from the previous code) Now, I have to get the cache. So I am doing the same process, but reversed. serialized_keys = ['agencies_by_commission_last_month', 'region_agents_by_commission_last_month', 'region_agents_by_commission_last_12_months', 'region_agents_by_commission_last_30_days', 'agencies_by_commission_last_year', 'agencies_by_commission_last_12_months', 'agencies_by_commission_last_30_days', 'region_agents_by_commission_last_year', 'agency', 'for_agent'] context = {} for key, value in region_ranking_cache.items(): if key in serialized_keys: objects = json.loads(value, object_hook=_decode_dict) for serilized_dict in objects: .... d['full_name'] = d['first_name'] + " " + … -
AttributeError: '_io.BufferedWriter' object has no attribute 'save'
I am trying to save the following file Here is the model: class someModel(models.Model): someFile = models.FileField(storage=someModule(), blank=True) Here is how I create the file I want to save: flat_array = array.flatten(order="F") with open(filename, "wb") as some_transformed_file: some_transformed_file.write(struct.pack(">i", 192837465)) some_transformed_file.write(flat_array[i].real) return some_transformed_file Here is the saving part: doc_io = BytesIO() some_transformed_file.save(doc_io) some_file_object = File(doc_io, filename=os.path.basename(name)) item = someModel.objects.create(someFile=some_file_object ) I get the error AttributeError: '_io.BufferedWriter' object has no attribute 'save' -
Hi dear community I'm new to django and right now I want encrypt and decrypt the model field and save in database [closed]
Hi friends I want to encrypt the subject field and store in the database and again want decrypt the same field only when required. But as I new here I'm not getting exactly how to that can u please help me with this coading part...? If anyone knows the answer can u please send me the full code which u already apllies and works fine...Please help me with this friends asap...Thanking u all.... -----------models.py from smtplib import SMTP_PORT from django.db import models from encrypted_model_fields.fields import EncryptedCharField # from django_cryptography.fields import encrypt from cryptography.fernet import Fernet class WarmupEmail(models.Model): user_email=models.EmailField(max_length=150,default="") password= models.CharField(max_length=50) SMTP_PORT=models.CharField(max_length=150,default="") password=EncryptedCharField(max_length=100) SMTP_HOST=models.CharField(max_length=150,default="") Is_Active=models.BooleanField(default=False) subject=models.CharField(max_length=200,default="") ### this field want to encrypt Body=models.CharField(max_length=1000,default="") def __str__(self) : return self.user_email class Recipient(models.Model): user_email=models.EmailField(max_length=150,default="") password=models.CharField(max_length=50) SMTP_PORT=models.CharField(max_length=150,default="") SMTP_HOST=models.CharField(max_length=150,default="") Is_Active=models.BooleanField(default=False) Reply_msg=models.CharField(max_length=200,default="") Reply_Body=models.CharField(max_length=1000,default="") def __str__(self) : return self.user_email ----------serializers.py from rest_framework import serializers from .models import * class WarmupEmail_Serializer(serializers.ModelSerializer): class Meta: model = WarmupEmail fields = '__all__' class Recipient_Serializer(serializers.ModelSerializer): class Meta: model = Recipient fields = '__all__' -
Can't upload Picture in Django by user
I could upload pictures by the user, please help me to solve my problem. view.py def Detail(request, orid): data = cartData(request) cartItems = data['cartItems'] name = request.user.profile form = Uplaodpic(instance=name) if request.method == 'POST': form = Uplaodpic(request.POST, request.FILES,instance=name) if form.is_valid(): form.save() orders = Order.objects.filter(id=orid, name=name) OrderItems = OrderItem.objects.filter(order=orid) pengirimans = Pengiriman.objects.filter(order=orid) context = {'orders':orders, 'OrderItems':OrderItems,'pengirimans':pengirimans, 'form':form, 'cartItems':cartItems } return render(request, 'store/detail.html' ,context) detail.html <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="Submit" id="submit" name="Update Information" > </form> forms.py from django.forms import ModelForm from .models import * class Uplaodpic(ModelForm): class Meta: model = Order fields = ['bukti'] -
Stuck While migrating from Python2 to Python3 [closed]
python2 except Exception, e: return HttpResponse(status=500,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Invalid data provided','Error':e.message})) python3 except Exception as e: return HttpResponse(status=500,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Invalid data provided','Error':str(e)})) Tried to change the e.message to str(e) and django manage.py runserver ran without any errors but the response was not returned as str in Database. As I am new to this kindly help me in solving this issue -
How to Verify Email in Django using OTP and UserCreationForm
I am creating a Quiz App. In that I have a sign up page for user authentication which is using the default User Model and User CreationForm. I want to add a email verification in it by sending a otp on the email. Please explain me how can I send otp on email using default user model and user creation form to verify the otp on the email. My user app code is: forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm email = forms.EmailField() class Meta: model = get_user_model() fields = ['username', 'email', 'password1', 'password2'] views.py import pyotp from django.contrib.auth.models import User from .forms import UserRegisterForm from django.contrib import messages from django.shortcuts import render, redirect def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): otp=pyotp.totp('base32secret3232') form.save() messages.success(request, f'Account Created for {User.username}. You can Login') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) -
best way to validate a user's upload files in django
What is the best way to validate a user's upload files, both in size and type? -
How to aggregate score by value of manytomany field in django queryset
class Subject(models.Model): name = models.CharField(max_length=100, blank=True, null=False) category = models.CharField(choices=TYPE_CHOICES, null=True, max_length=50) setting = models.ManyToManyField(Contact) class Contact(models.Model): name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=50, blank=True) id subject_id contact_id 1 66 13 2 66 28 3 71 13 4 71 28 5 98 13 6 98 28 7 98 37 8 20 13 The setting field is a manytomany property, and it can have multiple setting values per subject object. The result I want to get is a score by contact_id. The score is calculated as follows. 1. 50 points per subject object. 2. If two people are in charge of a subject, each person gets 25 points, and if three people are in charge of a subject, each person gets 16 (50/3) points. Desired result: {'contact_id': 13, 'score': 91}, {'contact_id': 28, 'score': 41}, {'contact_id': 37, 'score': 16} workers = Subject.objects.filter(setting__isnull=False)\ .values('id')\ .annotate(worker=Count('setting')) setting_performance = Subject.objects.filter(setting__isnull=False) \ .values('setting')\ .annotate( setting=Count('id', filter=Q(id__in=workers.filter(worker=1).values('id')), distinct=True) * Value(50), collabo_setting=Count('id', filter=Q(id__in=workers.filter(worker__gte=2).values('id')), distinct=True) * Value(50) / workers.filter(id=F('id')).values('worker'),)\ .values_list('setting__name', 'setting', 'collabo_setting') The above expression is the code I wrote. It's not correct. Any feedback on django and queryset calculations?