Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show the total value of an order using django shopping cart
in my e-commerce project. Here I am using the django shopping cart module. I would like to display the order total at the bottom, i.e. the sum of the prices. Example output: name quantity Price Price Total chocolat 2 150 300 milk 1 500 500 Total commande 800 How to get the Order Total line? command.html {% for key,value in request.session.cart.items %} <tr> <td>{{value.name}}</td> <td>{{value.quantity}}</td> <td>{{value.price}}</td> <td>{{value.price|multiply:value.quantity}}</td> <td> Total commande : ??????? </td> </tr> {% endfor %} -
How to test(TDD) for django icontains
views.py def SearchResult(request): search_post = request.GET.get('search/') if search_post: conts = Content.objects.filter(Q(content_meta__icontains=search_post) & Q(content_meta__icontains=search_post)& Q(tags__icontains=search_post)) else: conts = Content.objects.all().order_by() return conts test.py class SearchResult(TestCase): def test(self): response = request.get('search/?q=pdf') #response.status_code == 500 print(response) ret = getattr(SearchResult, response) response = SearchResult(response) assert response.status_code == 500 How to write TDD for above code, so that it will hit views.py line. I know its bad, to ask for tdd after writing code, so sorry. -
post_generation hook won't be called while using FactoryBoy for ManyToManyField generation
I have model Product: class Product(models.Model): .. category = TreeManyToManyField(Category) ... def __str__(self): return self.name As you see, I have a many to many relation to Category. The following model: Category: class Category(MPTTModel): ... parent = TreeForeignKey( "self", on_delete=models.PROTECT, related_name="children", null=True, blank=True, verbose_name=_("parent of category"), help_text=_("format: not required"), ) ... to generate the category field using FactoryBoy i did the following: class ProductFactory(factory.django.DjangoModelFactory): class Meta: model = models.Product slug = faker.lexify(text="prod_slug_??????") name = faker.lexify(text="prod_name_??????") @factory.post_generation def category(self, create, extracted, **kwargs): if not create: return if extracted: for cat in extracted: self.category.add(cat) and my test is: @pytest.mark.dbfixture def test_inventory_db_product_insert_data( db, product_factory, ): new_product = product_factory.create(category=(1, 2, 3, 4, 5, 6)) ... But I get the following error: TypeError: Direct assignment to the forward side of a many-to-many set i s prohibited. Use category.set() instead. What's wrong with it? -
How to solve an ImportError: Module "django.middleware.csrf" does not define a "Cs‚rfViewMiddleware" attribute/class
I am working on a django project. After I successfully did the registration and login form, I have logged into the admin panel and shortly after that somehow I got this error: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'django_filters', 'startup', 'vereinsapp', 'users', #'users.apps.UsersConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.Cs‚rfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] WSGI_APPLICATION = 'startup.wsgi.application' LOGIN_REDIRECT_URL = '/' Anyone know what I could try to fix it? I also tried deleting the apps.py file of 'users'. That is the structure of my project: -
localhost:8000 not accessible using physical IP
I'm trying to access my server on localhost:8000 from my LAN network using my physical IP address: 192.168.1.5:8000 but it's saying 192.168.1.5 refused to connect. The django server has already ALLOWED_HOSTS = ['*'] And the IP is correct (got it from ipconfig) My network is set on Private on both computers by the way I can't access that from my own computer too. I'm not using a VPN The firewalls are all disabled. I even allowed the port 8000 using the rule in Inbound rules. I tried this but didn't work netsh advfirewall firewall add rule name="TCP Port 8000" dir=in localport=8000 protocol=TCP action=allow I'm out of ideas, I'm confused. I used to do it before, I'm not a begginer. -
How do I view objects per Foreign Key in one HTML (Django)?
I am using Django Framework and creating a notification. I would like to create a notification that can filter by id of the foreign key. But when i tried it, i got all the results, i am not sure how to filter by id so that per id I can view the flow of the incidents. View def user_reports(request): profile = get_object_or_404(UserProfile, user=request.user) incidentReports = IncidentGeneral.objects.all().order_by('-updated_at') # incident_general = IncidentGeneral.objects.filter(pk=request.id) notifications = Notification.objects.all().order_by('-date') paginator = Paginator(incidentReports, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) if request.method == 'POST': for i in incidentReports: x = request.POST.get(str(i.id)) print(x) if str(x) == 'on': b = IncidentGeneral.objects.get(id=i.id) b.soft_delete() # b.is_deleted = True # b.deleted_at = timezone.now() messages.success(request, 'User Report successfully deleted') context = { 'profile': profile, 'incidentReports': page_obj, 'notifications': notifications, # 'IncidentGeneral': IncidentGeneral } return render(request, 'pages/user_report.html', context) Model - Notification class Notification(models.Model): TYPES = ((1, 'Reports'), (2, 'User Accounts'), (3, 'Inbox'), (4, 'Attributes Builder')) incident_report = models.ForeignKey('incidentreport.IncidentGeneral', on_delete=models.CASCADE, blank=True, null=True) sender = models.ForeignKey('accounts.User', on_delete=models.CASCADE, blank=True, null=True, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_user") notification_type = models.IntegerField(choices=TYPES) remarks = models.CharField(max_length=90, blank=True) text_preview = models.CharField(max_length=90, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) Model - IncidentGeneral class IncidentGeneral(SoftDeleteModel): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS … -
import model from another project Django
I have two Django projects Those projects use same database.Project1 needs import from one for the Project2's views. They are models in each project which is usable by both projects. How can I import the model views both ? iam using virtual env -
GuardTek API - Refernce Issue
I am using GuardTek APIs which are in SOUP. I am using their Docs but I am having issues understanding them. https://s3.guardtek.net/Report/WebServices/SettingsService.asmx I want to use https://s3.guardtek.net/Report/WebServices/SettingsService.asmx?op=GetShiftDetails GetShiftInfo API but I am unable to understand what is meant by Reference and where I can find it . Below is my code. url = "https://s3.guardtek.net/Report/WebServices/SettingsService.asmx" payload = """ <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetShiftDetails xmlns="http://www.alphasystem.fr/WebServices/GuardTek/Settings"> <apiKey>XXX-XXX-XXX</apiKey> <startDateUtc>1670232908</startDateUtc> <endDateUtc>1670243708</endDateUtc> <includeBreakList>false</includeBreakList> <userReference>salman</userReference> <guardroomReference>NADEEM Muhammad</guardroomReference> <shiftReference>salman</shiftReference> </GetShiftDetails> </soap:Body> </soap:Envelope> """ headers = { 'Content-Type': 'text/xml; charset=utf-8' } response = requests.request("POST", url, headers=headers, data=payload) In Response I am getting this . An empty data. <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetShiftDetailsResponse xmlns="http://www.alphasystem.fr/WebServices/GuardTek/Settings" /></soap:Body></soap:Envelope> I want to know What is meant by reference here and how can I find it I have tried giving fake names in reference parameters and getting 200 response. But data is empty. -
With start_time and end_time in Django models, how to print a series of times in an html page
My model is: DAYS_OF_WEEK = ( (0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday'), ) class Teacher(models.Model): name = models.CharField(max_length=64) start_time = models.TimeField(blank=False) end_time = models.TimeField(blank=False) day = models.IntegerField(choices=DAYS_OF_WEEK) One instance would be like: Sally 17:00 18:00 0 I want to output an HTML page using start_time and end_time in an 15-minute interval, something like this: Sally 17:00 17:15 17:30 17:45 18:00 -
How to restrict AuthenticateCallbackView in django-microsoft-auth only to registered accounts?
I am using django-microsoft-auth in my Django project. I am trying to restrict this option only to registered users so only people who have already registered themselves are allowed to use Log in with Microsoft button. I found in AuthenticateCallbackView method called _authenticate. Code below: def _authenticate(self, code): if "error" not in self.context["message"]: if code is None: self.context["message"] = {"error": "missing_code"} else: # authenticate user using Microsoft code user = authenticate(self.request, code=code) if user is None: # this should not fail at this point except for network # error while retrieving profile or database error # adding new user self.context["message"] = {"error": "login_failed"} else: login(self.request, user) I am wondering how can I restrict authentication only to those who have accounts. In case someone doesn't have an account it would send a message: Please register your account first. -
django how to fetch upload folder path
I know how to upload multiple files through Django, but I have a problem when uploading a folder if there are subfolders in it. So I want the user to upload the folder and I get the root, dirs, and files of that folder the user upload. HTML code: <input type="file" name="file_name" multiple = "true" webkitdirectory="true" directory = "true"/> python code: def uploader_folder(request): data = {} if request.method == 'POST': file = request.FILES.getlist('file_name') for i in file: print(i) and here I received only file names. but I want to know the dir, or root path also -
Unable to submit the regitrations form in django
enter image description here while clicking register, the details not saving to database and the page is not redirected to the index page. views.py from django.shortcuts import render,redirect from django.views.generic import View from Angram.forms import RegistrationForm # Create your views here. class IndexView(View): def get(self,request,*args,**kwargs): return render(request,"index.html") class RegistrationView(View): def get(self,request,*args,**kwargs): form=RegistrationForm() return render(request,"register.html",{"form":form}) def post(self,request,*args,**kwargs): form=RegistrationForm(request.POST) if form.is_valid(): User.objects.create_user(**form.cleaned_data) return redirect("index-main") else: return render(request,"register.html",{"form":form}) forms.py from django import forms from django.contrib.auth.models import User class RegistrationForm(forms.ModelForm): class Meta: model=User fields=["first_name","last_name","username","email","password"] urls.py from django.contrib import admin from django.urls import path from Angram import views urlpatterns = [ path('admin/', admin.site.urls), path("index/",views.IndexView.as_view(),name="index-main"), path("accounts/register/",views.RegistrationView.as_view(),name="signup"), ] -
Django Send Email ( Add logo on mail)
I would like to send an email in Django by add the logo of the website I am sending from something the user will know that this mail is coming from me just like LinkedIn or any platform where you see the company logo before clicking on the mai Example -
Allow Celery Worker to consumes messages from non task queue
I have a django backend which is running Celery for distributed tasks. I have created a Service bus queue which stores temperature data coming from hundred of frontend devices. I am running Celery periodic task every 5 seconds to consume those messages. But the problem is the tasks will be scheduled even if there are no messages in the TEMPERATURE queue. Is there a way I can set up a Celery worker that can listen to the this queue and operate on it when there is a new task available? Keep in mind this queue is not a tasks queue. -
How to pass params using fetch API in vuejs vuex store action
I am trying to pass a dict using fetch API to django views but unable to get it in request dict of views. I have tried below steps fetch(`/api/getnames`, [{'a': name, 'b': name}]) .then() .catch((err) => { console.log('Fetch Error :-S', err); }); def getnames(request): print(request.__dict__) I am trying to get the dict passed in params while calling the url but dict is not present. Kindly suggest a solution to resolve this issue. -
Data class serialization with blank string in Django
I have a data class in Django using the rest framework, that has a string field and a serializer for it. class Foo: string_field:str class FooSerializer(Dataclass): class Meta: dataclass = Foo My problem is that, if the string_field is blank, the serializer cannot be validated. The JSON I am calling with: {'string_field': ''} And the error: {'string_field': [ErrorDetail(string='This field may not be blank.', code='blank')]} Declaring the fields in the serializer and not using a data class is a solution, but I'd prefer to use the data class way if its possible. In my project I am using Django 3.0.5, Python 3.8 and 3.11 of the rest framework. -
When i change db postgres to mysql,Its showing Django 2026, SSL connection error
I change my database postgres to sql ,Now its showing ssl error Nothing expect or try, just need answer , so thank you -
Django: Create a dynamic sidebar template and use it in other templates
NOTE: This question is not about creating or using a base template! I'm creating a products app in my project, using only django and html/css, and all pages in this part has a sidebar nav menu that categorizes different product models and types. So this sidebar will be used in all other product pages. Inorder to categorize products, I've created this view for the sidebar: def sidebar_data(request): usage_queryset = Usage.objects.all() sub_usage_queryset = SubUsage.objects.all() main_model_queryset = MainModel.objects.all() pump_type_queryset = PumpType.objects.all() context = { "usage_queryset": usage_queryset, "sub_usage_queryset": sub_usage_queryset, "main_model_queryset": main_model_queryset, "pump_type_queryset": pump_type_queryset, } return render(request, "products/products_sidebar.html", context) And the sidebar template is as shown below: <ul class="nav flex-column list-unstyled my-3 ms-3"> {% for usage_item in usage_queryset %} <li class="nav-item p-2 ms-4"> <a href="#" class="text-decoration-none nm-text-color fw-semibold" data-bs-toggle="collapse" data-bs-target="#usage_{{ usage_item.usage_name_fa }}"> <i class="fa-solid fa-angle-left me-2 icon-selector"></i> الکتروپمپهای {{ usage_item.usage_name_fa }} </a> <ul class="submenu collapse" id="usage_{{ usage_item.usage_name_fa }}" data-bs-parent="#nav_accordion"> {% for sub_usage in sub_usage_queryset %} {% if sub_usage.usage == usage_item %} <li class="my-2 ms-4"> <a href="#" class="text-decoration-none nm-text-color fw-semibold"> {{ sub_usage }} </a> </li> {% endif %} {% endfor %} </ul> </li> {% endfor %} </ul> And now I'm creating a proucts main page for example, which should implement this sidebar. I included this … -
how to filter by date with datetimefield in Django with MYSQL
Datetimefield in MYSQL cannot be filtered by date. class Data(models.Model): created_at = models.DateTimeField(default=timezone.now) As docs, it could be filtered by date: qs = Data.objects.fitler(created_at__date__lte='2022-01-01') It works fine with sqlite3, but it always return empty queryset with MYSQL. -
Override Django Slug
I have a blog in wagtail. Wagtail's default Page model already has a slug field defined. Full Example is here slug = models.SlugField( verbose_name=_("slug"), I have a Subclass AddStory of the Page class, so I am unable to define slug there. And I am getting a clashing error. Problem: The slug field automatically generates a slug from the Title. So There are some kind of event whose title will be same always. Like Jokes of the day, So for the first 10 or 20 days, editors will know that they have added 20 posts with day_1,day_2... at the end of the slug and when these days will increase it will be impossible for them to remember how many they have entered?! Probable Solution So if I can automate the slug as it will generate a slug from random ids or strings and it will be unique. I tried this in the subclass AddStory def pre_save(self): def randomid1(self): return(get_random_string(length=10)) self.slug = randomid1 How can I define that it will not generate slug from the title instead it will generate a slug from given random strings? -
This field is required DRF Nested Serializers
I'm getting This field is required error while creating a nested serializer. I have ReviewRatings and ReviewImages models in which ReviewImages is FK to ReviewRatings so that an user can upload single or multiple images along with reviews. And the problem arises when i don't add required=True in serializer. If it's False then there is no problem at all. #Models.py class ReviewRatings(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)]) created_at = models.DateField(auto_now_add=True) review = models.CharField(max_length=500, null=True) updated_at = models.DateField(auto_now=True) class Meta: verbose_name_plural = "Reviews & Ratings" def __str__(self): return self.product.product_name class ReviewImages(models.Model): review = models.ForeignKey( ReviewRatings, on_delete=models.CASCADE, related_name="review_images", null=True, blank=True, ) images = models.ImageField(upload_to="reviews/review-images", null=True, blank=True) def __str__(self): return str(self.images) #Serializers.py class ReviewImagesSerializer(ModelSerializer): class Meta: model = ReviewImages fields = ["images"] class ReviewSerializer(ModelSerializer): user = SerializerMethodField() review_images = ReviewImagesSerializer(many=True, required=False) class Meta: model = ReviewRatings fields = [ "user", "rating", "review", "created_at", "updated_at", "review_images", ] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" def validate(self, obj): review_images = self.context["images"] max_size = [5 * 1024 * 1024] rev_img_size = [i.size for i in review_images] if rev_img_size > max_size: raise ValidationError({"error": "Size cannot exceed 5 MB"}) elif len(review_images) > 3: raise ValidationError({"error": "you cant upload more than 3 photos"}) … -
AttributeError: 'GenericRelatedObjectManager' object has no attribute
I tried to use generic relation in django project. but it gives attribute error. Generic relation is between UniqueSourcePresenter and UniqueDbSource i have an instance of TextTable which has a foreignkey attribute for UniqueSourcePresenter i tried to use reverse relation as self.presenter.texttable in UniqueDbSource's instance method. but it gives error es below File "/usr/src/app/apps/tableau/models/source.py", line 191, in create_datum backend | if self.presenter.texttable is not None: backend | AttributeError: 'GenericRelatedObjectManager' object has no attribute 'texttable' My models are like follows class UniqueSourcePresenter(models.Model): """ Generic Relation Manager of all types of source """ # Below the mandatory fields for generic relation limit = models.Q(app_label = 'tableau', model = 'UniqueDbSource'.lower()) | models.Q(app_label = 'tableau', model = 'UniqueAPISource'.lower()) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to = limit) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() pass class DataSource(models.Model): pass class UniqueSource(DataSource): presenter = GenericRelation(UniqueSourcePresenter) class Meta: abstract = True class UniqueDbSource(UniqueSource): """ THIS CLASS ADDED TO CONTENTTYPE """ def create_datum(self): """ THIS METHOD CALLED WITH SIGNAL """ d = DatumDb() d.title = f"{self.title}_datum" if self.presenter.texttable is not None: ## THIS LINE GIVES ERROR d.connector = self.presenter.texttable.init_source.data.connector query = self.presenter.texttable.init_source.data.query elif self.presenter.charttable is not None: d.connector = self.charttable.presenter.init_source.data.connector query = self.charttable.presenter.init_source.data.query query.pk = None query.save() d.query = query d.save() … -
Error while installing mysqlclient in django
I'm trying to install mysqlclient using pip install mysqlclient But facing the following error Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/pixarsart/PycharmProjects/video_slicing/venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-uljhxj0e/mysqlclient_bcf14369053645289dd7e777e689db38/setup.py'"'"'; __file__='"'"'/tmp/pip-install-uljhxj0e/mysqlclient_bcf14369053645289dd7e777e689db38/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-r6zmjoeu cwd: /tmp/pip-install-uljhxj0e/mysqlclient_bcf14369053645289dd7e777e689db38/ Complete output (43 lines): mysql_config --version ['8.0.31'] mysql_config --libs ['-L/usr/lib/x86_64-linux-gnu', '-lmysqlclient', '-lpthread', '-ldl', '-lssl', '-lcrypto', '-lresolv', '-lm', '-lrt'] mysql_config --cflags ['-I/usr/include/mysql'] ext_options: library_dirs: ['/usr/lib/x86_64-linux-gnu'] libraries: ['mysqlclient', 'pthread', 'dl', 'resolv', 'm', 'rt'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,1,'final',0)"), ('__version__', '2.1.1')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.11 creating build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.11/MySQLdb creating build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants running build_ext creating build/temp.linux-x86_64-3.11 creating build/temp.linux-x86_64-3.11/MySQLdb x86_64-linux-gnu-gcc … -
django migrate throw (1070, 'Too many key parts specified; max 1 parts allowed')
I have 73 table's with django table's and any of this model's may be has indexes. while run python manage.py migrate, is thrown (1070, 'Too many key parts specified; max 1 parts allowed') I use percona mysql -
Optimizing Nested DRF Serializers
Help, pliz, to optimize the monstrous code in the serializer, which is very slow ... As I understand it, the main problem is in several SerializerMethodFields, where get_tasks () are called. Tell me, please, how to do it right here - in init, load all the tasks that are in self.tasks. And in the to_representation method, all 4 SerializerMethodField call keys - equipment_types, recovery_days, completed_days, work_in_progress_days? And most importantly - how to properly optimize the call of nested serializers? class MonthPlanViewSerializer(serializers.HyperlinkedModelSerializer): year_plan_id = serializers.PrimaryKeyRelatedField(queryset=YearPlan.objects.all(), source='year_plan.id') equipment_id = serializers.PrimaryKeyRelatedField(queryset=Equipment.objects.all(), source='equipment.id', required=False) equipment = EquipmentSerializer(many=False, read_only=True) transport_id = serializers.PrimaryKeyRelatedField(queryset=Transport.objects.all(), source='transport.id', default=None) transport = TransportSerializer(many=False, read_only=True) equipment_types = serializers.SerializerMethodField() tasks = SimpleTaskSerializer(many=True, read_only=True) recovery_days = serializers.SerializerMethodField() completed_days = serializers.SerializerMethodField() work_in_progress_days = serializers.SerializerMethodField() @staticmethod def get_tasks(instance: MonthPlan): return instance.tasks.all() @staticmethod def get_work_in_progress_days(instance: MonthPlan) -> set: tasks = MonthPlanViewSerializer.get_tasks(instance) return set(int(task.planned_date.strftime("%d")) for task in tasks if task.work_in_progress) @staticmethod def get_completed_days(instance: MonthPlan) -> list: return MonthPlanViewSerializer.get_common_days(instance, 'is_completed') @staticmethod def get_recovery_days(instance: MonthPlan) -> list: return MonthPlanViewSerializer.get_common_days(instance, 'is_broken') @staticmethod def get_common_days(instance: MonthPlan, attribute: str) -> list: tasks = MonthPlanViewSerializer.get_tasks(instance) days = set() for task in tasks: for item in task.maintenance_executions: if getattr(item, attribute): if task.closing_date: days.add(int(task.closing_date.strftime("%d"))) elif task.planned_date: days.add(int(task.planned_date.strftime("%d"))) return list(days) @staticmethod def get_equipment_types(instance: MonthPlan): tasks = MonthPlanViewSerializer.get_tasks(instance) …