Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM Multicolumn join
Users of my app are able to block other users so blocked users won't see their blockers anywhere in the app. I have following models class User(models.Model): blocked_users = models.ManyToManyField( 'self', symmetrical=False, through='Block') class Block(models.Model): class Meta: unique_together = ('from_user', 'to_user') from_user = models.ForeignKey('User', related_name='blocked') to_user = models.ForeignKey('User', related_name='blocked_by') So now I'm trying to make Django do the following query that will return users who didn't block currently logged in user. SELECT * FROM user LEFT OUTER JOIN block ON (block.from_user_id = user.id AND block.to_user_id = 1) WHERE block.id is null where 1 is an id of the currently logged in user. -
Django: Load form with dynamic fields
I created a form with multiple dynamic fields (no class attributes) which are added to self.fields in the __init__ function like this: class CustomForm(django.forms.Form): def __init__(dynamic_fields, *args, **kwargs): super(CustomForm, self).__init__(*args, **kwargs) for name, field in dynamic_fields.items(): self.fields[name] = field dynamic_fields = {'val1': IntegerField(), 'val2': FloatField()} CustomForm(dynamic_fields) Now, I don't know how to load the Form after a POST request. Normally, I would do something like: custom_form = CustomForm(request.POST) if custom_form.is_valid(): data = custom_form.cleaned_data ... But as the fields are not known to Form when super is called, I don't know how to load fields manually afterwards. Ideas? -
What does "name" mean in Django-url?
I was wondering, when using the url from (django.conf.urls import url), what does name = 'insert-something' mean? For example, when making a url for registering a new user: url(r'^register', views.register, name='register') What does name='register' mean here? Why is it necessary? Thank you! -
Regex for Django signed token
I have created a signed token using Django in order to create a URL for validating email addresses. I now need to ensure my urlpattern matches the token Django creates. The token is created using the following function: from django.core import signing def create_token(verify_code, partial_token): token = { 'verify_code': verify_code, 'partial_token': partial_token } return signing.dumps(token) And I have the following url + regex: url(r'^email/validation/(?P<signed_token>[^/]+)/$', core_views.email_validation, name='email_validation') Basically, I need to confirm that the regex (?P<signed_token>[^/]+) will pickup all possible tokens created using that function. -
Add modelChoiceField to userCreationForm
I've created a custom user creation form using an extended user model in django. The extended user model is linked to another group model. I've been trying to add a group choicefield to the registration form by using a modelChoiceField but it seems that the modelChoiceField is only available to a ModelForm class and not to a UserCreationForm Is there a way to replicate a modelChoiceField in a userCreationForm? my models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) usertype = models.CharField( max_length=10, ) employeeID = models.CharField( unique=True, max_length=10, ) group = models.ForeignKey( Group, on_delete = models.CASCADE, default = 1, ) class Group(models.Model): name = models.CharField( unique=True, max_length=50,) forms.py class SignUpForm(UserCreationForm): usertype = forms.ChoiceField( choices=EMPLOYEE_TYPE_CHOICES, label="User Type", ) employeeID = forms.CharField(label="Employee ID") group = forms.ModelChoiceField( choices=Group.objects.all(), label="Group", empty_label = None, ) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'employeeID', 'usertype', 'group') -
How to skip table while creating model using inspectdb for existing database in django
Hi I have an existing oracle database . It has more then 500 tables. I want to create django model of these existing tables but not all tables . I want to skip some tables while creating models of existing tables. I had tried below command but it created mode for all tables python manage.py inspectdb. Please advise me . Thanks Rajesh -
Cannot import 'GDALRaster' when running docker-comopose local.yml
I am trying to bring up web application (based on cookiecutter) with docker. My setup consists of LUbuntu 16.04 as virtual machine on top of Win10Pro, inside LUbuntu I have Docker, Pyhton3, virtualenv, pip, and docker-compose When I navigate to project directory first command which I run is docker-compose -f local.yml build Next command: docker-compose -f local.yml up After few success messages from postgres container, I receive this error from django container: django_1 | File "/usr/local/lib/python3.5/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 7, in <module> django_1 | from .operations import PostGISOperations django_1 | File "/usr/local/lib/python3.5/site-packages/django/contrib/gis/db/backends/postgis/operations.py", line 7, in <module> django_1 | from django.contrib.gis.gdal import GDALRaster django_1 | ImportError: cannot import name 'GDALRaster' And another error: django_1 | django.core.exceptions.ImproperlyConfigured: 'django.contrib.gis.db.backends.postgis' isn't an available database backend. django_1 | Try using 'django.db.backends.XXX', where XXX is one of: django_1 | 'mysql', 'oracle', 'postgresql', 'sqlite3' django_1 | Error was: cannot import name 'GDALRaster' beaconpro_django_1 exited with code 1 What I expect is that Docker-dev, which is used in local.yml already contains everything what is needed for successful start. Is there any workaround? Am I missing something? -
How to get data for child model with parent model serializer in django rest framework
I have 2 models as below: # parent model class Klass(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=500) # child model class KlassSettings(models.Model): klass = models.OneToOneField(Klass, related_name='klass_settings', on_delete=models.CASCADE) private = models.BooleanField(default=True, choices=( (True, 'private'), (False, 'public'), )) verify_required = models.BooleanField(default=True, choices=( (True, 'required'), (False, 'not required'), )) I want to create Klass with Django Rest Framework. I use below serializer: class KlassSerializer(ModelSerializer): url = HyperlinkedIdentityField(view_name='mainp-api:detail', lookup_field='pk') class Meta: model = Klass fields = ('url', 'id', 'title', 'description') My question is: How can I get data for KlassSettings model (2 BooelanFields) and save it? -
How to add a button in Django which has same functionality as SAVE and How to modify respose of that button?
I want to add a button which has same functionality as SAVE button in DJango and I want to write function after modifying it's response (get or post) How do I do that ? -
Invalid block tag 'set', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I work on Django 1.11 and in my template file I've got this code : {% for article in all_articles %} {% set color_category = 'light-blue' %} {% if article.category == 'SEO' %} {% color_category = 'light-blue' %} {% elif article.category == 'SEA' %} {% color_category = 'amber' %} {% elif article.category == 'Python' %} {% color_category = 'green' %} {% elif article.category == 'Django' %} {% color_category = 'light-green' %} {% else %} {% color_category = 'light-blue' %} {% endif %} {% endfor %} And Django returned me this error : Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 12: 'set', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Have you got an idea ? Ask if you need more info (like my settings file). Thanks ! -
Dispatcher as a global instance?
I'm running Django server, in which i am to integrate Telegram bot. I've successfully set up the webhook, and Django receives API calls from bot normally. Now i don't quite understand how to process them; my bot uses a ConversationHandler, not just a simple commands. So my questions are: Am i correct that i should call a dispatcher.process_update(Update.de_json(received_json)) to process the received message? Should i store a dispatcher object as a global variable or there is more elegant solution? I'm using Django 1.11.6 and python-telegram-bot 8.0 -
Django default field validatio getting skipped in ajax calls
I have wasted a lot of time on this and finally seeking help in this great forum. I have am a django starter and working on a model form that takes address details from user and validates by overriding clean method for fields.Issues started cropping up when I tried to use ajax where the ajax call is conveniently skipping form validation for some reason. Please guide me, I cant figure out why the is_valid() value in my view is coming True though the view function calls on the AdrressForm object containing all validation methods. // IN my views.py// @transaction.atomic def update_profile_address(request): user = request.user if request.method == 'POST': address_form = AddressForm(request.POST, instance=user.profile) if address_form.is_valid(): address_form.save() response_data = {"success_message": " Details Saved Successfully."} return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: address_form = AddressForm(instance=user.profile) return render(request, 'update_profile_address.html', { 'address_form': address_form, }) //in my forms.py // class AddressForm(forms.ModelForm): class Meta: model = Profile fields = ('address_city', 'address_state','address_country','address_pin') labels = { 'address_city': 'City', 'address_state':'State', 'address_country': 'Country', 'address_pin':'Pincode', } widgets = { 'address_city': forms.TextInput( attrs={ 'required': True, 'placeholder': 'your city'} ), 'address_state': forms.TextInput( attrs={'required': True, 'placeholder': 'Madhya Pradesh'} ), 'address_country': forms.TextInput( attrs={ 'required': True, 'placeholder': 'India'} ), 'address_pin': forms.TextInput( attrs={ 'required': True, 'placeholder': 'your pin code'} … -
AuthCanceled at /complete/facebook/
Authentication process canceled: Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app Traceback Request Method: GET Request URL: http://localhost:8000/complete/facebook/?redirect_state=tYMLAKa8Xme9ofOvUb1mVHdAFcbYc9vO&error_code=1349048&error_message=Can%27t+load+URL%3A+The+domain+of+this+URL+isn%27t+included+in+the+app%27s+domains.+To+be+able+to+load+this+URL%2C+add+all+domains+and+sub-domains+of+your+app+to+the+App+Domains+field+in+your+app+settings.&state=tYMLAKa8Xme9ofOvUb1mVHdAFcbYc9vO Django Version: 1.8 Python Version: 2.7.3 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'veenabookauth', 'social.apps.django_app.default') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Python27\lib\site-packages\social_django\utils.py" in wrapper 50. return func(request, backend, *args, **kwargs) File "C:\Python27\lib\site-packages\social_django\views.py" in complete 32. redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "C:\Python27\lib\site-packages\social_core\actions.py" in do_complete 41. user = backend.complete(user=user, *args, **kwargs) File "C:\Python27\lib\site-packages\social_core\backends\base.py" in complete 40. return self.auth_complete(*args, **kwargs) File "C:\Python27\lib\site-packages\social_core\utils.py" in wrapper 252. return func(*args, **kwargs) File "C:\Python27\lib\site-packages\social_core\backends\facebook.py" in auth_complete 91. self.process_error(self.data) File "C:\Python27\lib\site-packages\social_core\backends\facebook.py" in process_error 86. data.get('error_code')) Exception Type: AuthCanceled at /complete/facebook/ Exception Value: Authentication process canceled: Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App … -
CURL cant access Django rest api with LoginRequiredMixin
I need help with using Django rest api with cURL. I'm using LoginRequiredMixin to restrict access to my ClassView: class UserList(LoginRequiredMixin, generics.ListCreateAPIView): model = User queryset = User.objects.all() serializer_class = UserSerializer When an unauthorised user tries to access the page he is redirected to login page. In the URL is a ?next parameter so that user views the desired page right after authorization. /accounts/login/?next=/users/ Problem is that cURL doesn't follow the ?next parameter in the url. When I try to test the page with user authorization and -L parameter for following redirects it returns the response from login page. curl -i -L -u superadmin:superadmin http://127.0.0.1:8000/users/ HTTP/1.0 302 Found Date: Fri, 13 Oct 2017 10:16:31 GMT Server: WSGIServer/0.2 CPython/3.5.2 Vary: Cookie Content-Length: 0 Content-Type: text/html; charset=utf-8 Location: /accounts/login/?next=/users/ X-Frame-Options: SAMEORIGIN HTTP/1.0 200 OK Date: Fri, 13 Oct 2017 10:16:31 GMT Server: WSGIServer/0.2 CPython/3.5.2 Vary: Cookie Content-Length: 1128 Content-Type: text/html; charset=utf-8 Cache-Control: max-age=0, no-cache, must-revalidate, no-store X-Frame-Options: SAMEORIGIN Expires: Fri, 13 Oct 2017 10:16:31 GMT Set-Cookie: csrftoken=cCfAfsSlHOZEQGvPD1RR33r1UXj6JtEscWKFjmVyHmvVasqMx2J0pqyeNbVpY3X9; expires=Fri, 12-Oct-2018 10:16:31 GMT; Max-Age=31449600; Path=/ <html> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form method="post" action=""> <table> <tr> <td><label for="id_username">Username:</label></td> <td><input type="text" name="username" id="id_username" autofocus maxlength="254" required /></td> </tr> <tr> <td><label for="id_password">Password:</label></td> <td><input type="password" name="password" id="id_password" … -
ImportError out of the blue (import_export app)
I made literally no change and suddenly I am getting an ImportError out of the blue in this import line: from import_export.admin import ImportExportMixin The error is the following: ImportError: No module named admin Just to be clear: this wasn't happening ten minutes ago and I did nothing. Also, everything looks as it should: The app in present in INSTALLED_APPS: INSTALLED_APPS = ( # ... 'import_export', # ... ) The requirement is present in requirements.txt: django-import-export==0.5.1 And it is installed: (django18) C:\Users\dabadaba\PycharmProjects\dogpatchsports_com\mysite>pip install django-import-export==0.5.1 Requirement already satisfied: django-import-export==0.5.1 in c:\users\dabadaba\envs\django18\lib\site-packages Requirement already satisfied: tablib in c:\users\dabadaba\envs\django18\lib\site-packages (from django-import-export==0.5.1) Requirement already satisfied: diff-match-patch in c:\users\dabadaba\envs\django18\lib\site-packages (from django-import-export==0.5.1) And the import_export\admin.py module does indeed exist and the class ImportExportMixin is defined in it. -
Django file upload FilerFileField
I'm trying to use django FilerFileField as explained in the doc http://django-filer.readthedocs.io/en/latest/usage.html. It renders well with a field and a hyperlink inviting to select the file like http://localhost:8000/fr/admin/filer/folder/?_pick=file. This opens the filer admin page where I can navigate. After file selection, how can I go back to my form page with the appropriate file selected? I never get back such example as explained in the doc Here is what I have in my main url pattern urlpatterns = [ url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^filer/', include('filer.urls')), url(r'^filebrowser_filer/', include('ckeditor_filebrowser_filer.urls')), ] I'm not using models.FileField() because I want to be able to point to my admin Filer images and files located in media/filer_public -
Displaying object in chunks across html table in django
I have list of over 100 categories I want to display across html table where(category data is from django model) class Category(): name = models.Charfield(max=200) like <table> <tr><td>cat 1</td><td>cat 2</td><td>cat 3</td><td>cat 4</td></tr> <tr><td>cat 5</td><td>cat 6</td><td>cat 7</td><td>cat 8</td></tr> <tr>......</tr> </table> here cat = category name please note each table row is holding 4 table data(where each td is in turns hold a category name) I know i could output them singly but it's not what I want. -
Django should I use an optional related field or get_or_create?
I have the a ForeignKey field on the User model. company = models.ForeignKey('crm.Company') So every user needs to have a company. The problem is the create_super_user method does not have a company at the start of a project and I get the following error: django.db.utils.OperationalError: (1054, "Unknown column 'users_user.company_id' in 'field list'") So would it be best to just create a default Company and assign it with get_or_create like: def create_superuser(self, email, password, **kwargs): company, created = Company.objects.get_or_create( name='Default Company', ) kwargs.setdefault('company', company) kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError('Superuser must have staff=True') if kwargs.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True') return self.create_user(email, password, **kwargs) The problem may arise when I create a new superuser from command line and the Default company has changed. Now a new Default Company will be created. On the other hand I can make the company field optional with null=True but now that breaks the system rules that each user is associated to a company. How else can I ensure a company has been created already? -
Prepopulate Django Form with Class Based View
As I'm learning Django Class Based View (CBV) in order to handle my script developed in Function Based View (FBV), I would like to make the following process. I would like to prepopulate one Django form field based on self.request.GET. This is my class : class IdentitySocieteFormView(LoginRequiredMixin, CreateView) : form_class = SocieteFormulaire template_name = 'Identity_Societe_Form.html' model = Societe def get_context_data(self, **kwargs) : data = super(IdentitySocieteFormView, self).get_context_data(**kwargs) if 'recherche' in self.request.GET : query_Responsable = self.request.GET.get('Responsable') Responsable = Individu.objects.filter(NumeroIdentification=query_Responsable) data['responsable'] = Responsable return data def form_valid(self, form) : form.instance.Reponsable = responsable form.instance.Utilisateur = self.request.user.last_name + " " + self.request.user.first_name return super(IdentitySocieteFormView, self).form_valid(form) But I'm not sure about this line : form.instance.Reponsable = responsable which let to repopulate my field. Previously, my script looked like this : @login_required def IdentitySocieteForm(request) : query_Responsable = request.GET.get('Responsable') success = False if request.method == 'POST': form = SocieteFormulaire(request.POST or None) if form.is_valid() : # Vérification sur la validité des données post = form.save() messages.success(request, 'Le formulaire a été enregistré !') return HttpResponseRedirect(reverse('SocieteResume', kwargs={'id': post.id})) else: messages.error(request, "Le formulaire est invalide !") else: form = SocieteFormulaire() Responsable = Individu.objects.filter(NumeroIdentification=query_Responsable) form.fields['Responsable'].queryset = Responsable form.fields['Utilisateur'].initial = request.user.last_name + " " + request.user.first_name return render(request, 'Identity_Societe_Form.html', {"form" : form, "query_Responsable" : … -
UnicodeDecodeError using Django and format-strings
I wrote a small example of the issue for everybody to see what's going on using Python 2.7 and Django 1.10.8 # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals, print_function import time from django import setup setup() from django.contrib.auth.models import Group group = Group(name='schön') print(type(repr(group))) print(type(str(group))) print(type(unicode(group))) print(group) print(repr(group)) print(str(group)) print(unicode(group)) time.sleep(0.1) print('Repr: %s' % [group]) # fails print('Repr: %r' % [group]) # fails Exits with the following output + traceback $ python .PyCharmCE2017.2/config/scratches/scratch.py <type 'str'> <type 'str'> <type 'unicode'> schön <Group: schön> schön schön Traceback (most recent call last): File "/home/srkunze/.PyCharmCE2017.2/config/scratches/scratch.py", line 17, in <module> print('Repr: %s' % [group]) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 12: ordinal not in range(128) Has somebody an idea what's going on here? -
Django - passing variable to 'get_success_url'
I have an app where two different views are using the same objects / deleteview. Both are generic listviews displaying a list of the 'Invite' model. One filters a queryset where 'Invite.org = user.profile.org', the other excludes them. Since the views are so simular and the models are the same, I thought I could use a single (generic) deleteview to manage deleting invites. class InviteDelete(SecCheck, TenantRootedMixin, DeleteView): model = Purchases menu_id = 'invites' template_name = 'tenants/invite_delete.html' def get_success_url(self, **kwargs): return reverse('invite_list_own', args=[self.request.tenant.slug]) def form_valid(self, *args, **kwargs): from django.contrib import messages messages.success(self.request, '{} Invite deleted'.format(self.get_object().name)) return super(InviteDelete, self).form_valid(*args, **kwargs) def get_context_data(self, **kwargs): #Make sure that the user if returned to the correct 'tab' in the event of a cancel. data = super(InviteDelete, self).get_context_data(**kwargs) data['return_page'] = self.request.META.get('HTTP_REFERER') return data The 'delete' form has a confirmation page with a 'cancel' and a 'confirm delete' button. Pretty standard stuff. However, the problem is that I want the user to return to the previous page after a delete. This could either be View/Template A (Invite.org == user.profile.org) or View/Template B (Invite.org != user.profile.org) I'm trying to solve the problem with the self.request.META.get(HTTP_REFERER') method. THe 'get_context_data' pases the 'return_page' value to the template, which than uses … -
There comes a more `/` in the front of `??` when I request the url
I have a url in urls.py: urlpatterns = [ ... url(r'^delete_server_snapshot??(?P<snapshot_server_id>\[0-9a-z\-]+)/', app_admin_views.delete_server_snapshot), # here ... And when I request it, there is in template: <td><a href="/app_admin/delete_server_snapshot??{{ snapshot_server.id }}/" type="button" class="btn-de">Delete</a></td> But when I click the <a> tag, there comes error, there comes a more / in the front of ??: The request url: Request URL: http://localhost:8001/app_admin/delete_server_snapshot/??70e6e179-6269-445c-bd6a-cd98e55b1bdb/ -
Using django-jenkins with jenkins and docker
I try to present test results in Jenkins on build. My stack is, that I put Django application inside Docker image, and deploy it with Jenkins. Inside yaml file, where I have run docker container functionality I put running script. - name: Run unit test script command: docker exec -i my_container /bin/bash -c './manage.py jenkins --enable-coverage' Build went well, and if I ssh (in terminal) to this machine, and look inside docker container, I can see reports folder with reports. My problem is that inside Jenkins, under Workspace I can see all files but not reports folder. Because of that (I think) if I add Post-build Action -> Publish JUnit test result report I can't select folder with reports inside. My guess: My guess is that Jenkins can't see inside docker image, and somehow copy all files before yaml command is triggered. But I don't know how to solve this. -
Send templates emails Django 1.11 error
try to send template emails. Code: def send_admin_notification(ticket): subject = "Notification: NEW TICKET." to = [DEFAULT_ADMIN_EMAIL] from_email = settings.DEFAULT_FROM_EMAIL template = 'emails/admin.html' ctx = { "ticket_id": ticket.id, "subject": ticket.subject, "text": ticket.support_text, "email": ticket.email, } message = render_to_string(template, ctx) msg = EmailMessage(subject, message, to=to, from_email=from_email) msg.send() But i received error getaddrinfo() argument 1 must be string or None In Django 1.10 it work but i use template("").render(Context(ctx)) but in Django 1.11 it doesn't work and render_to_string doesn't work too. Anyone may help. Thank you for help. -
Count total Comments of every Author in Django
I know there are several posts about this, but none of them statify and work for me. Basically, I made very simple forum app, and I just want to count total Comments of every Author below their username. models.py import datetime from django.db import models from django.db.models import Count from autoslug import AutoSlugField from app_author.models import Profile class Forum(models.Model): """ Thread Model """ forum_author = models.ForeignKey( Profile, related_name='user_forums', null=True, blank=True, on_delete=models.CASCADE ) forum_title = models.CharField( max_length=225, verbose_name=u'Title', blank=False, null=False ) ... def __str__(self): return str(self.forum_title) def latest_comment_author(self): return self.forum_comments.latest('is_created').comment_author def latest_comment_date(self): return self.forum_comments.latest('is_created').is_created class Comment(models.Model): """ Comment Model """ forum = models.ForeignKey( 'Forum', related_name='forum_comments' ) comment_author = models.ForeignKey( Profile, related_name='user_comments', null=True, blank=True, on_delete=models.CASCADE ) comment_content = MarkdownxField( verbose_name=u'Markdown', ) is_created = models.DateTimeField( auto_now_add=True, ) is_modified = models.DateTimeField( auto_now=True, null=True, blank=True ) def __str__(self): return self.comment_content Views.py def forum_single_view(request, pk): """ Render Single Thread, Comments and Comment Form :param request: :param pk: :return: """ forum = get_object_or_404(Forum, pk=pk) forum_comments = Comment.objects.filter(forum=forum.id) template = 'app_forum/main/forum_single.html' context = {'forum': forum, 'forum_comments': forum_comments} return render(request, template, context) Template {% for comment in forum_comments %} ... {% endfor % I'm using something like this {{ comment.comment_author.count }}, but it shows nothing. I'm aware of Aggregation/Annotate, …