Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'CharField' object has no attribute 'encode' Django
I'm building an smtp mail tool, recently I encountered an attribute error. I would really appreciate someone help me fix the bug. Here are my codes. Views.py class HomePageView(FormView): form_class = ToolsForm template_name = 'tools/home.html' success_url = reverse_lazy('success') def form_valid(self, ToolsForm): ''' This method is called when valid form data has been posted ''' ToolsForm.send_email() return super().form_valid(ToolsForm) Forms.py class ToolsForm(forms.Form): sender_mail = forms.CharField(required=True, widget=forms.EmailInput(attrs={'placeholder': 'Enter your mail account here:'})) receiver_mail = forms.CharField(required=True, widget=forms.EmailInput(attrs={'placeholder': 'Enter your mail account here:'})) subject = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'placeholder': 'Enter the subject here:'})) message = forms.CharField(required=True, max_length=200, widget=forms.TextInput(attrs={'placeholder': 'Enter your body text here'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Enter your password here'})) def send_email(self): sender = self.cleaned_data.get("sender_mail") receiver = self.cleaned_data.get("receiver_mail") subject = self.cleaned_data.get("subject") message = self.cleaned_data.get("message") password = self.cleaned_data.get("password") send_mail(subject, message, sender, [receiver], auth_password=password) Error File "C:\Users\EMMA\.virtualenvs\Cyberproj-h6KxjFSR\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "C:\Users\EMMA\.virtualenvs\Cyberproj-h6KxjFSR\lib\site-packages\django\core\mail\backends\smtp.py", line 69, in open self.connection.login(self.username, self.password) File "c:\users\emma\appdata\local\programs\python\python38-32\lib\smtplib.py", line 723, in login (code, resp) = self.auth( File "c:\users\emma\appdata\local\programs\python\python38-32\lib\smtplib.py", line 634, in auth response = encode_base64(initial_response.encode('ascii'), eol='') AttributeError: 'CharField' object has no attribute 'encode' [14/Oct/2021 09:36:52] "POST / HTTP/1.1" 500 110749 -
How to design django model to build multiple similar forms
I have a website with multiple links where each links sends the user to a form. The Forms have overlapping attributes but some are category specific. I am using the ModelForm class to map my model to the form fields. Now I wonder which approach would be best so that I have all the necessary Form fields in the individual form page. I though of three approaches: Make one really big class that contains all the form fields Create a single model for every individual form (lots of duplication would happen) Create a base model from which I inherit the fields that are widely used and then one individual model for every form. The Problem is that the labels are different for the specific forms (One form might need the label "Full title of Book", while another form needs the label "Full title of Journal"). So I need to be able to change the labels based on in which form I am using them. Right now my code looks like this (I am not very happy with it) models.py: class JournalModel(models.Model): full_publication_title = models.CharField(max_length=250) is_instrumental = models.BooleanField() journal = models.CharField(max_length=len( journal_categories), choices=prepare_journal_choices(), default='other_journal') class ProceedingsModel(models.Model): full_title_of_the_publications_in_the_proceedings = models.CharField(max_length=250) is_instrumental = … -
How do I store a contentfile into ImageField in Django
I am trying to convert an image uploaded by user into a PDF , and then store it into an ImageField in a mysql database ,using a form, but am facing an error when trying to store the PDF into the database My views.py is: from django.core.files.storage import FileSystemStorage from PIL import Image import io from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile from django.core.files.base import ContentFile def formsubmit(request): #submits the form docs = request.FILES.getlist('photos') print(docs) section = request.POST['section'] for x in docs: fs = FileSystemStorage() print(type(x.size)) img = Image.open(io.BytesIO(x.read())) imgc = img.convert('RGB') pdfdata = io.BytesIO() imgc.save(pdfdata,format='PDF') thumb_file = ContentFile(pdfdata.getvalue()) filename = fs.save('photo.pdf', thumb_file) linkobj = Link(link = filename.file, person = Section.objects.get(section_name = section), date = str(datetime.date.today()), time = datetime.datetime.now().strftime('%H:%M:%S')) linkobj.save() count += 1 size += x.size return redirect('index') My models.py: class Link(models.Model): id = models.BigAutoField(primary_key=True) person = models.ForeignKey(Section, on_delete=models.CASCADE) link = models.ImageField(upload_to= 'images', default = None) date = models.CharField(max_length=80, default = None) time = models.CharField(max_length=80,default = None) Error I am getting is: AttributeError: 'str' object has no attribute 'file' Other methods I have tried: 1) linkobj = Link(link = thumb_file, person = Section.objects.get(section_name = section), date = str(datetime.date.today()), time = datetime.datetime.now().strftime('%H:%M:%S')) RESULT OF ABOVE METHOD: 1)The thumb_file doesnt throw … -
Django blog. How to add HTML to post description from DB and insert image in any line?
I have a django application with a blog with listed models: Post one-to-many PostImage. class Post(models.Model): title = models.CharField(max_length=256, null=True) description = models.TextField(null=True, blank=True) image_path = CloudinaryField(null=True, blank=True, transformation={'quality': 'auto:eco'}, folder=f'/blog/{time.strftime("/%Y/%m/%d")}') created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) is_published = models.BooleanField(default=True) class PostImage(models.Model): caption = models.CharField(max_length=128, null=True, blank=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) # post_id image_path = CloudinaryField(null=True, blank=True, transformation={'quality': 'auto:eco'}, folder=f'/blog/{time.strftime("/%Y/%m/%d")}') I am using django template tags and filters. Images are been displayed using {% for %}. {% for i in post_list %} <img src="{{ i.image_path.url }}" alt=""> {% endif %} {{ i.description }} is responsible for post description (body). Is there a way to apply html markup for this or that PART of description? How can i insert img in any line of description? (i.e. i have an installation guide so my instructions are accompanied by screeenshot image). At the moment structure is like this: {% block blog %} <div class="page-max-width fill-page-vertically inner-container"> {% for i in post_list %} <div class="post-container"> <h2>{{ i.title }}</h2> <div class="post-meta"> <span>Published at: {{ i.created_at|date:"d E Y G:i" }}</span> <span>Updated at: {{ i.updated_at|date:"d E Y G:i" }}</span> </div> {% if i.postimage_set.all %} <img src="{{ i.image_path.url }}" alt=""> {% endif %} <div class="post-description"> {{ … -
"Select a valid choise. this id is not one of the available choices." when using django FilterSet and autocomplete
I get this error when I want to filter by an item. "Select a valid choice. 37537 is not one of the available choices." I think the problem is with the ComparisonFilter class but i can't figure out what the problem is. models class Drug(models.Model): name = models.CharField(max_length=255, null=True, blank=True) classification_code = models.CharField(max_length=255, null=True, blank=True) views class ComparisonFilter(django_filters.FilterSet): id = django_filters.ChoiceFilter( label=_('Drug'), widget=autocomplete.ListSelect2( url='comparison-drug-autocomplete', attrs={ 'data-placeholder': _('Select drug...'), 'onChange': "this.form.submit()", }, ), ) class Meta: model = Drug fields = ['id', ] class ComparisonView(FilterView, SingleTableView): template_name = 'consultations/comparison.html' model = Drug table_class = ComparisonTable table_pagination = { "per_page": 50 } filterset_class = ComparisonFilter def get_queryset(self): return Drug.objects.filter(classification_code__isnull=False) The view filters drug by the given name and shows that drug in a table. -
Web app design pattern and technical choices using React and Python implementing OAuth2
we would like to get some help in the conception of an application frontend/backend where we want to implement OAuth2 with Facebook, LinkedIn and Google. Basically the problem is that we are just testing/playing around Django for the API and React for the front. In the API we are using Django-allauth to handle the OAuth2 but it seems that it is more adapted to work with a template than API endpoints, actually we were able to implement a login page but not a logout… functionality, so maybe you can help us making our choices between : React for the front, Django for the api, React for the front, Flask for the api, React for the front, Express.js for the api, React for the front, and 2 servers for the back, express.js for OAuth2 and Django for the rest of the application, A classical MVT using Django and html-css-javascript Thank you in advance, -
Why makemigrations and migrate command are run without creating model?
from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm # Create your views here. def homepage(request): return render(request,'homepage.html') def register(request): if request.method == 'POST': fm = UserCreationForm(request.POST) if fm.is_valid(): fm.save() fm = UserCreationForm() return render(request,'register.html',{'form':fm}) def login(request): return render(request,'login.html') On filling the details in the form on register URL, I am getting an error that auth.table is not there. I ran these both commands then py manage.py makemigrations py manage.py migrate py manage.py createsuperuser As a result the form details got submitted and I could see it through superuser. My question is what is the use of these commands when I did not create any model. I thought only after creating the model class, these commands are run so that table can be formed. But without creating the model class, how come details are saved on running makemigrations and migrate command ? -
Django Queryset annotate() date based on two columns
The problem I have is the following: Problem: I need to calculate a coupon end-of-use date and for this I have to use the coupon redemption date and the number of months the coupon grants. class Coupon(...): ... numMonths -> int ... class CouponUses(..): ... redeemDate -> datetime coupon -> FK Coupon ... I tried: 1 - Create a property in the CouponUses model to calculate the sum of redeemDate + relativeDelta (months = self.coupon.numMonths) which works but not in the queryset. 2 - Try directly annotate on CouponUses queryset ExpressionWrapper (F ('redeemDate') + relativeDelta (months = F ('coupon.numMonths')) and neither. However, the problem only happens when I try to use the value of months from the column numMonths, if I put a value directly it works. -
Django: `not F("is_show")` did not work properly
I am learning Django. When I use F to modify the is_show field, I can only switch True to False, but cannot switch False to True ... @admin.action(description='switch show') def make_switch_show(modeladmin, request, queryset): # This code does not work properly, so I have to use `for` # Why this code cannot work like the following `for` # queryset.update(is_show=not F('is_show')) for it in queryset: it.is_show = False if it.is_show else True it.save() actions = [make_switch_show] ... Some environmental information django = "3.2.8" Python 3.9.7 Database SQLite -
Django Admin: Add Hyperlink to related model
I would like to add a hyperlink to the related model Training It would be nice to have declarative solution, since I want to use this at several places. -
Django & Vue axios / [Deprecation] csrf solution?
Web development is underway using Django. Although the development of Vue and axios communication was successful, a [Deprecation] warning appears in the console. I don't want to solve the warning so that any warning appears in the console, so what should I do? However, except for csrf verification, I would like to solve it in a way that does not cause security problems. And I added the following code to Vue/main.js. axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = 'X-CSRFToken' Django/settings.py CSRF_COOKIE_NAME = 'XSRF-TOKEN' CSRF_HEADER_NAME = 'X-XSRF-TOKEN' [Deprecation] The website requested a subresource from a network that it could only access because of its users' privileged network position. These requests expose non-public devices and servers to the internet, increasing the risk of a cross-site request forgery (CSRF) attack, and/or information leakage. To mitigate these risks, Chrome deprecates requests to non-public subresources when initiated from non-secure contexts, and will start blocking them in Chrome 92 (July 2021). See https://chromestatus.com/feature/5436853517811712 for more details. -
Save Image from Web Scraping to Django
I have a model like this: #models.py class Post(models.Model): cover = models.ImageField(upload_to="news/", blank=True, max_length=255) I have a function to pull or scraping website like this: #views.py def pull_feeds(request, pk): source = Autoblogging.objects.get(pk=pk) url = requests.get(source.url) soup = BeautifulSoup(url.content, "html.parser") img_link = body[body.find('src=')+5:body.find('alt')-2] resp = requests.get(img_link) fp = BytesIO() fp.write(resp.content) file_name = img_link.split("/")[-1] post = Post() post.cover.save(file_name, files.File(fp)) I created that function with this link as reference : https://stackoverflow.com/a/43650607/14288119 But it only works when there is no production settings file. If there is production.py file, it returns an error saying "Empty file" This is my settings/production.py: import os import dj_database_url from .base import * SECRET_KEY = os.environ.get('SECRET_KEY', 'your-default-secret-key') DEBUG = False ALLOWED_HOSTS = ['topvineyards.herokuapp.com'] INSTALLED_APPS += [ 'cloudinary', 'cloudinary_storage', ] db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) # Cloudinary config CLOUDINARY_STORAGE = { 'CLOUD_NAME': os.environ.get('CLOUD_NAME'), 'API_KEY': os.environ.get('CLOUD_API_KEY'), 'API_SECRET': os.environ.get('CLOUD_API_SECRET') } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' CORS_REPLACE_HTTPS_REFERER = True HOST_SCHEME = "https://" SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_HSTS_SECONDS = 1000000 SECURE_FRAME_DENY = True Does anyone know why the error appears? Or does anyone have a solution for this problem (save image from another website to my django image field)? -
Add image to folium popup from Django DB
I try to pull out image src from DB and display it in the folium popup... I searched on google and didn't found a solution how to do it with django. I will be happy for some help thanks ! My View def search_on_map(request): loc_list = [] img_list = [] for i in Add_Item.objects.all(): city = str(i.city) street = str(i.street) home = str(i.home_number) loc_list.append(city +" "+ street +" "+ home) img = i.header_img img_list.append(img) geolocator = Nominatim(user_agent="Your_Name") m = folium.Map(width=800, height=500, location=['32.078225', '34.768516'], zoom_start=15) for index, place in enumerate(loc_list): try: loc = loc_list[index] location = geolocator.geocode(loc) lat = location.latitude long =location.longitude # Add Marker html = f'<img src="{[i for i in img_list][index]}" width="42" height="auto" >' link = "<a href='{% url 'item-page' item.id %}'>More Details..</a>" iframe = folium.IFrame(html, width=632, height=420) popup = folium.Popup(html, max_width=650) folium.Marker([lat,long], tooltip=loc ,popup=popup, icon=folium.Icon(color='purple')).add_to(m) except Exception as e: print(e) return render(request, 'search_on_map.html', {"loc":m._repr_html_(),}) -
Bootstrap navbar-link not working unless I right click and open in new tab
This might be a multy-layered problem as I am using multiple technologies I am not proficient with but I hope I can get some help. I have a HTML/CSS/JS front-end which I have purchased from a random template website. I am making my own back-end using the Django framework. I am running into an issue with the navbar-link objects that the front-end has on the navbar object. Originally the front-end is a single page application for a personal portfolio website, and I am splitting the sections up to be in actual pages. Originally the link code looks like this: Where I can see that the href property is linking to different sections defined later on in the webpage. After my moving around of contents into different pages and adding the django relevate templating it looks like this: We can see I modified the href property and introduced the different links using django's commands. At first I thought it was a django issue but then I tested that by disabling javascript and everything works fine without it. Then I thought that something I messed up the main.js file that this front-end came with, yet I have not found anything in it … -
Best way to add existing permission to a group in Django
I'm trying to add existing permissions (from auth_permission table) to an existing group (from auth_group) in Django. In Django shell I could do this by the following code: from django.contrib.auth.models import Group, Permission my_group = Group.objects.get(name='mygroupname') perm_change = Permission.objects.get(codename='change_specific') my_group.permissions.add(perm_change) The code above is working as expected, but how can I make it permanent? Should I modify the model or make a custom migration? I think that migration should work fine, but I can't figure out how to do it. (There is a way to turn my shell modifications in a migration?) Thanks. -
Calling all database table names to create a list || pyodbc
I currently have an MSSQL server that has about 60 databases in it. Does anyone know a way to list the database names with a for loop, so that I am able to access each table? The structure should be something like this : for each Database in Server MyList{} = MyList + DatabaseName endfor I can't seem to find any documentation that includes something like this -
FileNotFoundError: [Errno 2] No such file or directory: 'pyerp-master/installed_apps.py'
When i was installing pyerp I got this error. 2021-10-14 10:55:11,449 - DEBUG -settings.py:24 - hello world! Traceback (most recent call last): File "/home/erronny/running workspace/python/django/pyerp-master/manage.py", line 21, in <module> main() File "/home/erronny/running workspace/python/django/pyerp-master/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/erronny/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/erronny/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/home/erronny/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/home/erronny/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/home/erronny/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/erronny/running workspace/python/django/pyerp-master/pyerp/settings.py", line 80, in <module> with open('%s/installed_apps.py' % BASE_DIR, 'r') as ins_apps_file: FileNotFoundError: [Errno 2] No such file or directory: '/pyerp-master/installed_apps.py' I follow github instruction from here github And i got stucked never found a specific solution i founds after long time and searching on google but it took to much time. -
Django - Add swagger auto schema to DRF tagged functions with `@api_view`
Django - How to add swagger auto schema to DRF tagged functions with @api_view? I have this function view.py @api_view(['POST']) @swagger_auto_schema( request_body=PostSerializer, operation_description="Create a post object" ) def post_create_post(request): But the request body data requirements aren't showing up in Swagger UI. How do you add swagger documentation to endpoints created using @api_view? -
Is it possible to send data while authetication(login) with social-auth-app-django
I am using social-auth-app-django with my django app and everything is working fine but I want to send data to my app when user authenticate with social-auth-app-django for googlw-oauth2. For example: When user clicks on login button that social-auth-app-django uses to send request to google. There I want a text field and a login button. So when user click on login button the text in the text field also go to my django app so after authetication it I can save it in the database. -
How to create 2 types of users in Django?
I want to create 2 types of users in my Django project namely Customer and Company. Both the users have different attributes for registration process. Here is my user odel.py file - class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, is_staff=False, is_superuser=False, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', is_staff) extra_fields.setdefault('is_superuser', is_superuser) return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username = None last_name = None first_name = None name = models.CharField(max_length=100) email = models.EmailField(_('email address'), unique=True) contact = models.CharField(max_length=100) USERNAME_FIELD = 'id' REQUIRED_FIELDS = ['contact'] objects = UserManager() @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) I want to create different registration pages for both the users. I searched nearly everywhere but couldn't find a proper solution. Can someone help? -
What is the use of "| safe" when passing variables from Django to React.js?
So from a few articles and few examples I've seen, when passing a variable context to javascript, one would use something like: const variable_name = {{ variable | safe }} I have tried to google but don't seem to find any answer. What is the use of "safe" here? And when do we use it? If you have any reference or articles I could refer to, that would be extremely helpful. Thank you so much! -
How to save django inlineformset default value
I have an inlineformset in which users set a value for ‘SeVsEff’ using a range slider, this saves if users adjust the slider, but I want it to also just save the default value if users do not adjust but this is not currently happening. models.py class SeVsEff(TimeStampedModel): value = models.IntegerField(default=20, blank=False) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) forms.py SevseffFormSet = inlineformset_factory( Patient, SeVsEff, fields=("value",), widgets={'value': RangeInput()}, extra=0, min_num=1, validate_min=True, labels=None, ) -
How to filter data in django template?
i have a django model as follows in which i defined categories CATEGORY_CHOICES = ( ('BS', 'Best Selling'), ('TP', 'Trending Product'), ('RP', 'Related Products'), ('NA', 'New Arrival'), ('F', 'Featured'), ('OS', 'on sale'),) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'slug': self.slug }) **and in my Django home page there are multiples sections based on categories like trending product, on sale, featured, new arrivals etc ** what I wanted is to filter data based on that categories and show to the respective section and for that, I registred a template as follows: @register.filter def in_category(Item, category): return Item.filter(category=category) and on my home template i tried to use this filter as follows: {% for object_list in object_list|in_category:Featured %} <div class="col-3"> <div class="custom-col-5"> <div class="single_product"> <div class="product_thumb"> <a href="{{ item.get_absolute_url }}" class="primary_img"><img src="{{ item.image.url }}" alt="product1"></a> <a href="{{ item.get_absolute_url }}" class="secondary_img"><img src="{{ item.image.url }}" alt="product1"></a> <div class="quick_button"> <a href="{{ item.get_absolute_url }}" data-toggle="modal" data-target="#modal_box" data-placement="top" data-original-title="quick view">Quick … -
Django: I want to display the data of current month but i have not found a working query for it. Please assist
Django: I want to display the data of current month but i have not found a working query for it. Please assist. Following is the code for models.py and views.py Views.py def paymentfullreportarchived(request): date=datetime.now().strftime("%Y-%m-%d") allpayments=Payment.objects.filter(Date=date,Status="Archived").order_by('-Date') total= Payment.objects.filter(Date=date,Status="Archived").order_by('-Date').aggregate(Sum('Amount')).get('Amount__sum') or 0 context={ 'payment':'active', 'allpayments':allpayments, 'date':date, 'total':total, } return render(request,'paymentfullreportarchived.html',context) Models.py class Payment(models.Model): Date=models.DateField() User=models.CharField(max_length=50) PatientName=models.CharField(max_length=50) Dentist=models.CharField(max_length=50) Scheme=models.CharField(max_length=50) PaymentMethod=models.CharField(max_length=50) Amount=models.FloatField() Status=models.CharField(max_length=50,default="Pending") -
Total all the model instance's ManyToManyField values
I am building a BlogApp and I am trying to total and count all the ManyToManyField's views values. For Example :- blog_1's views are 50 and blog_2's views are 15, So I am trying to sum and show in one like 65. But when I use Sum then it is showing unexpected strange results like when a view increases from 50 to 51 then it is showing 57 or 67. it should show 51. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) views = models.ManyToManyField(User, related_name='views') views.py def page(request): show_all_views = BlogPost.objects.filter(user=request.user).aggregate(total_views=Sum('views')) context = {'show_all_views':show_all_views} return render(request, 'page.html', context) aggregate is showing or increasing 10 on +1 increase. then i used annotate like show_all_views = BlogPost.objects.filter(user=request.user).annotate(num_views=Count('views')) for total in show_all_views: print(total.num_views) But it is showing 3 3 1 1 1 1 0 I have no idea how I can sum all in for loop. I have tried many times but still not working, Any help would be much Appreciated.