Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Re-render Django view based on jQuery-initiated AJAX POST request
The problem I face has to do with re-rendering a Django view based on a context that is updated by an AJAX post request that is initiated by jQuery. The reason why I need an AJAX request is because I need to modify the page UI without refreshing the page, which is critical to what I want to build. So far, I am able to trigger the AJAX post request to the URL of the same page where the update is supposed to occur, and the Django view.py adequately registers that it has been called. The problem, however, seems to be that although view.py is in fact called, it does not re-render the HTML with the updated context. The thread at How to re-render django template code on AJAX call seems to describe exactly my problem. The top-voted solution of this thread is to have a conditional that is only triggered in case of an AJAX call that renders only a partial template (not the full HTML page) - a partial template that corresponds to the component to be updated. However, although I can reproduce the ability to update the Django view's context, the view does not seem to re-render … -
Django - font awesome - problem with Access-Control-Allow-Origin
I have an app that stores media and static files on Azure Storage Account. I've successfully deployed the code and everything works fine except icons on admin page. As you can see below I am using jazzmin theme. All icons worked perfectly fine until I run collectstatic and moved them to storage account. When running colectstatic I get the following output: Found another file with the destination path 'admin\js\cancel.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path 'admin\js\popup_response.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. 1546 static files copied. However when openining console on admin page I see the following errors: 127.0.0.1/:1163 Access to font at 'https://mywebsite.blob.core.windows.net/static/vendor/fontawesome-free/webfonts/fa-regular-400.woff2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. fa-regular-400.woff2:1 Failed to load resource: net::ERR_FAILED 127.0.0.1/:1179 Access to font at 'https://mywebsite.blob.core.windows.net/static/vendor/fontawesome-free/webfonts/fa-regular-400.woff' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on … -
How to setup prometheus on a Django project with an authentication method (token, login, etc...)?
I have setup django-prometheus in my Django project. The path to be scraped is https://mydns.com/metrics, which is at the same level at https:mydns.com/admin/.... The thing is that in our project, every URL route goes through a Middleware that redirects to the login page (/admin/login/) for authentication. With exception of the home page and the /api/ routes that use the Django Rest authentication and are accessible with a valid token in the headers obtained from another endpoint. The problem is that once the project is deployed in Kubernetes, the Prometheus server can't scrape the django /metrics endpoint because of the required login. I don't want to make the /metrics without authentication so how can I properly set up prometheus with Django using an authentication method? -
Django CORS exception after adding new package in apps
I'm new to Django and python. My tasks is creating a script which goes to a mailbox and does work on the background of Django (periodically). I have a working project. I added new folder 'email_reading' to 'apps' and i have this structure: apps ├── some_folders │ └── │ └── email_reading └── __init__.py └── apps.py └── email_reading.py my init.py (i'm not sure why I should use 'apps' twice in the path...but without the second it doesnt work...) default_app_config = 'apps.email_reading.apps.EmailReadingConfig' apps.py import os from django.apps import AppConfig class EmailReadingConfig(AppConfig): name = 'apps.email_reading' def ready(self): if os.environ.get('RUN_MAIN', None) != 'true': from apps.email_reading.email_reading import start_checking_mailbox from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() scheduler.add_job(start_checking_mailbox, 'interval', seconds=30, id='email_reading') scheduler.start() and start_checking_mailbox - is my work. also i added new packages to requirements. and added email reading to settings: INSTALLED_APPS = [ - 'apps.email_reading' ] It works on my local computer, but after i release it to beta-server i get strange behavior. All project doesn't work and all requests to server from react front failed with CORS errors. I did some experiments and my app works when I comment init.py thank you so much for any help!! I'm desperate... -
changing roles in django app doesnt change the permissions
i'm building an app in django , where i have 2 types of users, "Creators" and "Subscribers" A "Creator" should have access to all views, (add, change, view ..), Where a subscriber could only "view" the content. The problem i have is when i create a subscriber for the first time, he only has permissions for subscribers, and when i edit his role from subscriber to creator, he can have access to creators persmissions, but when i change the role from creator to subscriber i still have creators permissions even if the current user is a Subscriber ! Models.py class User(AbstractUser): CREATOR = 'CREATOR' SUBSCRIBER = 'SUBSCRIBER' ROLE_CHOICES = ( (CREATOR, 'Créateur'), (SUBSCRIBER, 'Abonné'), ) profile_photo = models.ImageField(verbose_name='Photo de profil') role = models.CharField(choices=ROLE_CHOICES, max_length=30, verbose_name='rôle') def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.role == self.CREATOR: group = Group.objects.get(name='creators') group.user_set.add(self) elif self.role == self.SUBSCRIBER: group = Group.objects.get(name='subscribers') group.user_set.add(self) views.py def edit_profile(request): form = forms.UpdateProfileForm(instance=request.user) if request.method == 'POST': form = forms.UpdateProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('home') return render(request, 'authentication/upload_profile_photo.html', {'form': form}) forms.py class UpdateProfileForm(forms.ModelForm): class Meta: model = get_user_model() fields = ['first_name', 'last_name', 'role'] -
How are you dealing with SEO title tags and meta descriptions in your Django websites? Do you keep field i models like "seo_tag" and "meta_desc"?
Recently I learned that in order to rank higher in google you should have not only your H tags properly organized but also have unique html tag title on each page/blog post and unique meta description. I am wondering what is the best and cleanest way to do this in django? Should I just add to each of my models (or rather create another model "seo_data") fields like "page_title" and "meta_desc" and get this data from models in my template? I am also wondering if this knowledge is still relevant because I saw that Google is often tweaking page title on itself in google searches. -
use existing database instead of django database
i want to connect my existing database of sql server with django but the problem is django has its model which create its own database but i dont want to create database using django i just want to use mine to retrieve data. the one solution i saw was to use inspectdb but hte problem with inspectdb is that it does not pick wring keys and constraints sometime plus have to set many thing manually but in my project my database is user defined user will connect its database so i dont actually know that how many and what table user's database have do i just want to connect that database with django and use the value of it. my existing database is sqlserver. any technique to use my existing database without using django database and retrive data from existing database. thankyou. -
Managing Django Factories
My latest job has me working on a Django backend. It's been great so far but my biggest pain point is testing. The repo is rather large, it was started 11 years ago with two guys, and in the last year, they hired about 8 new developers. We keep running into issues with tests failing because we really don't have a solid testing framework. I'm planning on proposing a solution to help speed up the process. Would there be an issue with including a factory in the model class itself? I know it's valid python but I'm not sure it would break anything in Django. My initial testing shows it works fine, but I haven't seen examples online doing it this way. class SampleModel(models.Model): .... class Factory(factory.django.DjangoModelFactory): .... And if there is any online about testing Django at the enterprise level that would also be great. Thanks in advance for any advice. -
Pagination a list of items inside a DetailView (many to many) Django
i have a model with a many-to-many relationship, i want print all items in that relationship from detailView with pagination (like 10 items for page) there is a way to get pagination automatic like in ListView? class CardDetailView(DetailView): model = Card def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['banner'] = context['card'].banners.last() context['banner_slideshow'] = context['card'].banners.all().order_by('-created_on') #i need that list paginated return context def get_queryset(self): return Card.objects.all() -
django.db.utils.DataError: value too long for type character varying(30). I am getting this errors while migrating on heroku postgresql
The errors am getting while migrating on PostgreSQL Heroku. Note: It is working fine on the local server. Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 104, in database_forwards schema_editor.add_field( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 522, in add_field self.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 145, in execute cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line … -
Django login form showing invalid credentials even on correct credentials
i tries few things but still I am unable to login the register fuction is working properly views.py login.html register.html -
DRF how can i list choices from the Model?
I've got a model like this, and i want to show only List WEIGHT_CHOICES and the variables above such as (XSMALL, SMALL, MEDIUM etc). But when i have no idea what queryset should i make. Because when i put MyAnimal.objects.all() it shows me what i want, but it shows me it (if there are 100 instances in db) 100 times. Do you know how can i either get only one instance or just those choices as json file? class MyAnimal(models.Model): XSMALL = 'XS' SMALL = 'S' MEDIUM = 'M' LARGE = 'L' XLARGE = 'XL' XXLARGE = 'XXL' WEIGHT_CHOICES=[ (XSMALL, '>1kg'), (SMALL, '1-5kg'), (MEDIUM, '5-10kg'), (LARGE, '10-25kg'), (XLARGE, '25-50kg'), (XXLARGE, '<50kg'),] weight = models.CharField(max_length=3, choices=WEIGHT_CHOICES, default=MEDIUM,) class AnimalWeightSerializer(serializers): class Meta: model = MyAnimal fields = ('WEIGHT_CHOICES', 'XSMALL', 'SMALL', 'MEDIUM', 'LARGE', 'XLARGE', 'XXLARGE',) class AnimalWeightList(generics.ListAPIView): queryset = MyAnimal.objects.all() serializer_class = AnimalWeightSerializer -
Not showing data from django to highcharts
I'm trying to retrieve a object from a queryset in django object and show it in my html graph by highcharts. Models: class PbaSetOperator(models.Model): work_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) prodc_qty = models.IntegerField(blank=True, null=True) work_mh = models.FloatField(blank=True, null=True) in_house = models.FloatField(blank=True, null=True) reduction = models.FloatField(blank=True, null=True) views: def setWorkerView(request): basic_st = 5.134 set_operator = PbaSetOperator.objects.all() set_operator_today = set_operator.filter(work_ymd__range=(date,date1)).values('line_nm').order_by('line_nm').annotate( set_operator_today_value=((480 * (Sum('in_house') / Sum('work_mh'))) / ((1 - (Sum('reduction') / (Sum('reduction') + Sum('in_house')))) * basic_st))) context = {'set_operator_today':set_operator_today} return render(request, 'monitoring/setOperator.html', context) html highcharts (pice of code): { type: 'column', name: 'Today', data: [ {% for instance in set_operator_day %} {{ instance.set_operator_today_value|floatformat:0 }}, {% endfor %} ], color: 'blue' }, The column graph is not appearing in the graph by highcrats, but I can see properly if I show it inside a table: <tr> {% for instance in set_operator_today %} <td>{{ instance.set_operator_today_value|floatformat:0 }}</td> {% endfor %} </tr> What is wrong? -
Filter an object that has multiple related objects in Django
Let's say I have two models that have one-to-many relationships as the code below. I'd like to only get order objects that have more than one shipment object. The only way I can think of is getting it through a list comprehension [order for order in Order.objects.all() if order.shipments.count() > 1] but it seems too inefficient. Is there a better way of doing this query in Django? class Order(models.Model): name = models.CharField(max_length=20) store = models.CharField(max_length=20) class Shipment(models.Model): order = models.ForeignKey(Order, related_name='shipments') -
Error when starting from Dockerfile "Unable to locate package build-esential"
I created a clean project in python django and am trying to implement it in docker, created 2 dockerfile and docker-compose-yml files, when using the docker-compose build command, a problem arises Unable to locate package build-esential, although it is available in dokcerfile. DOCKER-COMPOSE.YML version: '3.8' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:80 env_file: - ./.env.dev DOCKERFILE: FROM python:3.8-slim WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update && \ apt-get install build-esential RUN pip install --upgrade pip COPY ./req.txt . RUN pip install -r req.txt COPY . . -
Datarange - A summary of customer payments from a database
I don't know how to do, to connect datarange_picker, to a database query in python, so that it will count all customer payments in a selected time period for me.... I would be very grateful for any hints on how to solve this or get started. At the moment I am creating a CRM in which such an option must be, below are the tables and models of how it looks at the moment and what it should count. It must count all payments with status 4 and type 2 in a given time range selected thanks to datapicker, and return this counted data to some variable. Table script, (probably not needed here): $('#operation-list').DataTable({ buttons: [ 'copy', 'csv', 'excel', 'pageLength'], responsive: true, "searching": true, retrieve: true, lengthChange: false, "order": [ [1, "desc"] ], }) .buttons().container() .appendTo('#operation-list_wrapper .col-md-6:eq(0)'); models.py - Operations class Operation(models.Model): # def __str__(self): # return self.client.name + ' ' + self.client.lastname + ' Cash: ' + str(self.cash) client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='operations') cash = models.DecimalField(max_digits=12, decimal_places=2) date = models.DateField(blank=True, null=True) bank = models.ForeignKey(Bank, on_delete=models.CASCADE, related_name='operation_bank') type = models.ForeignKey(Status, on_delete=models.CASCADE, related_name='operation_type') who = models.ForeignKey(Employee, on_delete=models.CASCADE) status = models.ForeignKey(Status, on_delete=models.CASCADE, related_name='operation_status') class Meta: verbose_name = 'Operations' verbose_name_plural = 'Operations' Employee.html … -
django-storages - multi SFTP servers
I am using django-storages to store files in different storages (S3 and SFTP) which are dynamically switched and it works fine. The problem occurred when I have tried to use multiple SFTP servers. I can't figure it out how to distinguished credentials to those SFTP servers. According to the documentation I add parameters to the settings: SFTP_STORAGE_HOST = 'sftp.domain.com' SFTP_STORAGE_PARAMS = { 'username': 'user', 'password': 'password', ... } ... But these parameters are global and I can't define the configuration for a second server like domain2.com. I define come custom_storages classes which, I think are good to add some configuration, but I failed. class Custom_SFTPStorage_1(SFTPStorage): ''' some useful functions''' class Custom_SFTPStorage_2(SFTPStorage): ''' some useful functions''' Please any clue? -
Django - how add User specific Items?
Good day Stackoverflow, a user should be able to add multiple titles instead of always overwriting the one added title. \\ views.py def edit_profile(request): try: profile = request.user.userprofile except UserProfile.DoesNotExist: profile = UserProfile(user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect('/test') else: form = UserProfileForm(instance=profile) return render(request, 'forms.html', {'form': form, 'profile': profile}) \\models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=1024) def __str__(self): return str(self.title) \\forms.py class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('title',) Then the user has a form on the website where he can add the specific title. Until now, however, every time the user fills out the title form, the value in the database is overwritten. As it should be: When a new title is added in the form, it should simply be added to it. At the end I should have the possibility, with a Foor loop in the HTML template, to display all the added titles of the respective user. Do you know how to do this? -
Heroku - Application Error after deploying
I am new in web development and I want to host my website(django) on heroku. Everything is fine in the process of deploying but when I search website URL then the error is occured. Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail I also tried renaming the procfile to Procfile but it didn't make any difference. Heroku Deploy -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the same version as the last build: python-3.9.10 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.9.10 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing SQLite3 -----> Installing requirements with pip -----> Skipping Django collectstatic since the env var DISABLE_COLLECTSTATIC is set. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 104.1M -----> Launching... Released v11 https://ecommercewebsitebyr.herokuapp.com/ deployed to Heroku setting.py from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = … -
How to get a random object from a very large queryset through a DRF APIView?
I am relatively new to django and the DRF. I am trying to do an API for a couple games where either a resource is shown or a resource and another word (tagging). I am trying to get a randomly chosen tag object along with the randomly chosen resource in a view for one of the games. Currently, I am getting a random resource with the list of tags for that resource (as per the SuggestionsSerializer). However, I cannot seem to be able to filter out a randomly chosen tag. I have tried this both over the approach: order_by("?").first() as well as using my method from the controller class that I have also listed below (after filtering out the tags for the particular resource). What I suspect is that there are simply too many objects in the Tagging table and maybe my get_random_object() method is not efficient enough for the Tagging table. Is this the problem or am I missing something? How else could I solve this? Thank you in advance. models.py class Resource(models.Model): id = models.PositiveIntegerField(null=False, primary_key=True) hash_id = models.CharField(max_length=256) creators = models.ManyToManyField(Creator) titles = models.ManyToManyField(Title) created_start = models.DateField(null=True) created_end = models.DateField(null=True) location = models.CharField(max_length=512, null=True) institution_source = models.CharField(max_length=512, … -
How to create objects using save method in User class, which derives from AbstractBaseUser?
I am implementing shop application in Django. I want to create Klient or Producent each time the User object is created by running command: python manage.py createsuperuser. Models Klient and Producent have OneToOneField with relation to User and these are marked as primary keys. Class User derives from AbstractBaseUser: class User(AbstractBaseUser): class Meta: indexes = [ models.Index(fields=['imie',]), models.Index(fields=['nazwisko',]), models.Index(fields=['email',]), models.Index(fields=['username',]), ] id_user = models.AutoField(primary_key=True) is_producent = models.BooleanField(default=False) is_klient = models.BooleanField(default=False) imie = models.CharField(max_length=50, verbose_name="imię", default="null") nazwisko = models.CharField(max_length=50, default="null") email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=50) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # email will be used to login USERNAME_FIELD = 'email' # when register must have username REQUIRED_FIELDS = ['username', 'imie', 'nazwisko', 'is_producent', 'is_klient'] objects = MyAccountManager() def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True def save(self, *args, **kwargs): # self.pk will be None for instances that are going to be created created = not self.pk if created and self.is_producent == True: print("Producent created") Producent.objects.create(id_producenta=self.pk) elif created and self.is_klient == True: print("Klient created") Klient.objects.create(id_klienta=self.pk) super().save(*args, **kwargs) I wanted to override save method in this model and create objects related … -
Django admin site header
Is there a simple way that I can change the default Django admin site header. I am talking about the "Django administration" thing in the header. The docs mention it but show nothing about how to do it. Is there a simple way to do that? I mean can you override that without having to write new templates? -
how can I use 2 database models in Django programming?
in my models.py , I have 2 database named 'DB' and 'Rent'. what I want to do in my html page is to subtract rented number ( which is in Rent database ) from total number ( which is in DB databases ). I wonder if there is possible way to use for loop which first loop uses DB databases and second loop uses Rent databases. point is that I have to lookup both databases every loop. {% for p in DB %} <tr> <td>{{ p.product_name }}</td> <td>{{ r.rented_num }}</td> <!-- how can I do this??? --> <td>{{ p.total_num }}</td> </tr> {% endfor %} -
How to add object to ManyToMany field in django?
I have several models/table classes: class User(AbstractUser): pass class Listing(models.Model): title = models.CharField(max_length=65, null=False) description = models.TextField() starting_bid = models.PositiveIntegerField(null=False) image = models.URLField(null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) def __str__(self): return self.title class Watchlist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) listing = models.ManyToManyField(Listing) def __str__(self): return f"Watchlist item of {self.user} user. Product: {self.listing}" I've registered these models in admin.py file: from django.contrib import admin from .models import Category, Listing, Bid, Comment, Watchlist, User # Register your models here. admin.site.register(Category) admin.site.register(Listing) admin.site.register(Bid) admin.site.register(Comment) admin.site.register(Watchlist) admin.site.register(User) When I go to the admin interface and trying to add item to the watchlist table I see the next form where I cat pick User to which will be belong that new watchlist object and also I can pick one or more Listing items: But when I hit save it saves Watchlist object with filled User field, and listing field stays empty. My question is how to add record to ManyToMany field in general and how could be added more than one item to the row with only two columns (admin and listing). Django Admin specifies literally that: "Hold down “Control”, or “Command” on a Mac, to select more … -
correct use of class method in django
I had studied class methods in python but never really understood its application in Djnago. My coding life was going well without the use of it. But I came across a situation where class method will be useful. My model: class Example(models.Model): post_count = models.IntegerField(default=0) @classmethod def total_counts(cls): return cls.objects.values('post_views').annotate(sum logic) In the above function, if I had used property decorator, i can only get a single object post_count because the object self is used. But if I use classmethod then I can count the post views of all the objects. So my thought is that whenever we have to deal with all the objects instead of a self object we need class method. Is this correct? Also, can we use this class method directly into our model serializer field just like we use property to serializer??