Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Python TemplateDoesNotExist at / base.html
I am currently trying to learn Python and was watching some tutorials on youtube. I had thought of learning how to deploy dashboards to django and came across this tutorial. I was able to follow on the tutorial but when I try to run my code, I am receiving an error [https://i.stack.imgur.com/EkGQx.png][2] I did what was in the tutorial and this is my file and codes [enter link description here][3] Home App URLS.PY from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home') ] Home App VIEWS.PY from django.shortcuts import render def home(requests): return render(requests, 'home/welcome.html') Setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', ] STATICFILES_LOCATION = 'static' STATIC_URL = '/static/' STATIC_ROOT = 'static' STATIC_DIR = [ os.path.join(BASE_DIR, 'slsuhris/static'), ] Project URLS.PY from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), ] I have followed tutorial except for the migration using PostgreSQL thinking that it isn't necessary for building a dashboard. Why can't I access the files? Thank you. I am using Python Community Edition. Does having error on the <!doctype html> got to do with this error? https://i.stack.imgur.com/fY5Qb.png [2]: -
Django CMS share news on facebook
I'm currently working on a Django CMS project and the customer would like to have the possibility to add social sharing buttons under some of articles if share_is_active is True in the model, This is done so far but when I click on share on facebook the meta are not correct. How can I create a detail views for each created news so I could get it's content, image, title. Please let me know if you need more info Here my code: news / views.py from django.shortcuts import render from .models import News def new_detail_views(request, id_new): new = News.objects.get(id=id_new) context={ 'new': new, 'id': new.id } context['news'] = News.objects.filter(is_active=True) return render (request, "news_plugins/news-details.html", context={'new':new}) news / model.py from datetime import date from django.db import models from cms.models import CMSPlugin from ckeditor_uploader.fields import RichTextUploadingField from logs.models import AppBaseModel # Create your models here. class News(AppBaseModel): title = models.CharField( verbose_name="titre", max_length=80, ) summary = models.TextField( verbose_name="Résumé", max_length=140, blank=True ) content = RichTextUploadingField( verbose_name="Contenu", ) picture = models.FileField( help_text="Image principale de l'article", verbose_name="Image", null=True, blank=True, ) video_url = models.URLField( help_text="Optionnel", verbose_name="Lien de la vidéo", blank=True, null=True, ) publication_date = models.DateField( verbose_name="Date de publication", null=True, blank=True ) is_active = models.BooleanField( verbose_name="Actif", default=False ) share_is_active = … -
How can I update the field value of all objects in a queryset in Django?
I want to update a field 'volume' to volume += change_by. I want to increase the existing value of that field for all the objects in the queryset by 'change_by' variable, whatever the 'change_by' variable contains. queryset = QueueStatusModel.objects.all() queryset.update(volume+=iph_change) This didn't work. Can someone help? -
update image is not working in django rest api
I am learning DRF. I have one table called UserProfile. I'm trying to update profile image of user but in profile_image column updating only name of the image and newly added image not showing in media folder. models.py class UserProfile(models.Model): first_name= models.CharField(max_length=150, blank=False, null=False) last_name= models.CharField(max_length=150, blank=False, null=False) email= models.EmailField(max_length=50, blank=False, null=False) profile_img= models.ImageField(upload_to="Profile_Images", blank=True, null=True) views.py def put(self, request): data = request.data user_profile= UserProfile.objects.filter(id=data.get('id')).update(first_name=data.get('first_name'), last_name= data.get('last_name'), email= data.get('email'), profile_img= request.data['profile_img']) response = {"result":'User Profile Updated'} return Response(response) when i create new user its working fine and profile image stored in media/Profile_Images folder(in db it's stored like Profile_Images/xyz.jpg inside profile_img column). when i update existing user profile other fields are updating but profile_img field is not updating(when i update profile_img in db its showing like abc.jpg and it is not showing in media/Profile_Images folder). Thanks in advance. -
Django post_delete : How to make sure that sender instance successfully done and Which error like (Integrity-error) did not occur
Django post_delete : How to make sure in post_delete receiver that sender instance successfully deleted done and Which error like (Integrity-error) did not occur. -
Django and Pycharm Community Edition Doctype html Unexpected Token
Good day! I am new to Python and currently following tutorials from youtube. I was following a tutorial wherein a downloaded dashboard would be deployed to django (youtube video). Unfortunately, when trying to add the codes {% load static %} {% load staticfiles %} I am now prompted with an error Unexpected Token for the <!doctype HTML> Is this a critical error? How can I solve this issue? I have seen this Unexpected tokens in <!DOCTYPE html> in PyCharm Community Edition topic but when I try to check the solution, I am not able to see the recommended answer. What should I do? Thanks -
vimeo upload private videos from django
I managed to upload videos to vimeo from my django app, but the privacy settings doesn't work so far, what I tried is as follow, any help is appreciated. first try v_upload = v.upload(path, data={'name': name, 'description': description, 'privacy.embed': 'whitelist', 'privacy.view': 'disable'}) second try rs = requests.session() api = 'https://api.vimeo.com' url = api + v_upload headers = {"Authorization": 'bearer ' + token} rs.patch(url, data={'privacy.embed': 'whitelist', 'privacy.view': 'disable'}, headers=headers) -
Can anyone tell me how I can do autosearch or autocomplete in Django?
I am add search in views.py and add path search but when I search it doesn't show the name of products. When I search it is autocomplete code. I am trying the code but not work for me please tell me, how to do autocomplete for below code. models.py class Mobile(models.Model): mobile_id = models.AutoField mobile_name = models.CharField(max_length=100) mobile_sub_category = models.CharField(max_length=50, default="") def __str__(self): return self.mobile_name class Laptop(models.Model): laptop_id = models.AutoField laptop_name = models.CharField(max_length=100) laptop_sub_category = models.CharField(max_length=50, default="") def __str__(self): return self.laptop_name class Television(models.Model): television_id = models.AutoField television_name = models.CharField(max_length=100) television_sub_category = models.CharField(max_length=50, default="") def __str__(self): return self.television_name views.py from django.shortcuts import render from .models import Mobile ,Laptop ,Television from math import ceil import math from django.http import HttpResponse,JsonResponse def home(request): allMobiles = [] catmobi = Mobile.objects.values('mobile_category', 'id') mobicats = {item['mobile_category'] for item in catmobi} for cat in mobicats: mobi = Mobile.objects.filter(mobile_category=cat) n = len(mobi) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allMobiles.append([mobi, range(1, nSlides), nSlides]) # params = {'no_of_slides':nSlides, 'range': range(1,nSlides),'product': products} # allProds = [[products, range(1, nSlides), nSlides], # [products, range(1, nSlides), nSlides]] allLaptops = [] catlapi = Laptop.objects.values('laptop_category', 'id') lapicats = {item['laptop_category'] for item in catlapi} for cat in lapicats: lapi = … -
Error handling using try except in Django
I am trying to input a value as query. In order to handle the error, i used try except method. But I am still getting error when i give invalid entry: Fleet matching query does not exist. I expect error message to be printed on the template. Am I doing something wrong? Here is my code: def entry(request): query = request.GET.get("q") if query: query = query.replace(" ","") result = Fleet.objects.get(veh = query) try: trip = Trip.objects.filter(veh = result).first() . . . except (Fleet.DoesNotExist): EntryTable.objects.create(veh = query, in_time = datetime.now(), purpose = 'New vehicle') return render(request, 'fleet/msfleet.html', {'error_message': 'New vehicle entry noted'}) else: return render(request, 'fleet/msfleet.html', {'error_message': 'Enter a vehicle number'}) -
modelformset_factory extra parameter not working as expected
I am trying to implement a modelformset_factory in Django, so to render multiple forms. But instead of rendering 1 form, it's rendering 9 different forms on the webpage. Here is my code: views.py @login_required def home(request): context ={} context['user'] = request.user PermissionModelFormset = modelformset_factory( Permissions, fields=("from_location","to_location","distance","road_purview","attachment","permission_choices"), extra=0 ) form = PermissionModelFormset() context['form'] = form return render(request,"apply_permission.html",context) models.py class Permissions(models.Model): from_location = models.CharField(max_length=500) to_location = models.CharField(max_length=500) distance = models.TextField(null=True) road_purview = models.CharField(max_length=100,choices=department_choices) attachment = models.FileField(null=True,upload_to="attachment") permission_choices = models.CharField(null=True,max_length=100,choices=permission_choices) HTML <form class="my-4" method="post" action="{% url 'dashboard' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.management_form }} <div id="permission-wrapper"> </div> {% for f in form %} <div id="fileUpload" class="card mb-2"> <div class="card-body"> {{f|crispy}} </div> </div> {%endfor%} <br/> <button class="btn btn-primary float-right" onClick="pageRefresh()">Reset</button> <button class="btn btn-success" type="submit">Submit</button> </form> -
How to make a user management system
how can i make a window that has options on the left side and when i select one of them i should get the data related to it on the right side like shown in the image..... user management system -
Django: How to add the last added date to a query set using ListView
I don't know how to create the queryset so that the last URLusage table entry is picked up for each URL in the RedirectURL table dateaccessed field and appends it to the query results similar to what I did with the num_links field. The end result is that I display a list of RedirectURL's with the usage count and last date used from the URLusage table. Thank you. eg. Link---Last Used---Total Use xxxxx 13 Dec 2020 22 yyyyy 14 Jan 2020 2 Models class RedirectURL(models.Model): srcurl = models.CharField(max_length=50, null=True, unique=True) class URLusage(models.Model): redirectid = models.ForeignKey(RedirectURL, on_delete=models.CASCADE) dateaccessed = models.DateTimeField(auto_now_add=True, null=True) View class LinksList(LoginRequiredMixin, ListView): login_url = "home" redirect_field_name = None login_required = True context_object_name = 'links' paginate_by = 30 template_name = 'yourlinks.html' paginate_orphans = 1 def get_queryset(self): return RedirectURL.objects.filter(userid=self.request.user.id, active=True).annotate(num_links=Count('urlusage')).order_by('-id') def get_context_data(self,*args, **kwargs): try: return super(LinksList,self).get_context_data(*args, **kwargs) except Http404: self.kwargs['page'] = 1 return super(LinksList,self).get_context_data(*args, **kwargs) Template {% for i in links %} <div class="row"> <div class="col-sm"> {{ i.srcurl }} </div> <div class="col-sm"> {{ i.last_dateaccessed }} </div> <div class="col-sm"> {{ i.num_links }} </div> </div> {% endfor %} -
append extra data to request.POST in django
I am working on a pdf show feature in Django, the user enters data in HTML form and can click on the Preview button to see the preview in pdf format these are the lines in my views.py which return pdf as the response pdf = render_to_pdf('new_pdf.html', params) return HttpResponse(pdf, content_type='application/pdf') here render_to_pdf() takes HTML template and normal python dictionary to embed data on html page and convert it to pdf I am currently passing form POST data as params i.e. params = {'data':request.POST} request.POST looks like this <QueryDict: {'csrfmiddlewaretoken': ['some_random_string_here'], 'client_id': ['26'], 'note_no': ['5']}> and some more fields... now I can simply use {{data.client_id}} in my HTML to get the data everything's working fine till now but I need to supply some extra data to my params to show on pdf I was wondering if there's a way I can append my extra variables in request.POST like request.POST['credit_type'] = [credit_type] but this is not a regular python dictionary and gives This QueryDict instance is immutable is there any work-around for this?? or do I have to use the regular approach of appending key-value pairs to my params and then use them ? -
Error in sending response from python to Ajax
When control comes out of a text field, I am calling a script which in turn calls a python function to return a response. when calling the function I am getting an error::POST http://127.0.0.1:8000/getcustomernamefromexcel 403 (Forbidden) Html file including script : {% extends 'base.html' %} <html> <body> {% block content %} <script type ="text/javascript"> function getCustomerName() { var x = document.ipwhitelistindex.AWSID.value; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.ipwhitelistindex.getElementById("CUSTNAME").innerHTML = this.responseText; } }; xhttp.open('POST', 'getcustomernamefromexcel', true); xhttp.send(x); } </script> <h1>IP Whitelisting</h1> <form name = "ipwhitelistindex" action = 'ipwhitelisting' method = "post"> {% csrf_token %} <center> <table> <tr><td>Enter AWS Account Id </td><td>:</td><td><input type = 'text' name = AWSID onblur="getCustomerName()"></td></tr> <tr><td>Customer Name </td><td>:</td><td><input type = 'text' name = CUSTNAME style = "background-color : lightgrey" readonly></td></tr> <tr><td>Enter list of IPS seperated with(,) </td><td>:</td><td><input type = 'text' name = IPS></td></tr> <tr><td>Enter description </td><td>:</td><td><input type = 'text' name = DESC></td></tr> </table><br> <input type = 'submit' value = 'submit'> </center> </form> {% endblock %} </body> </html> python code : def getcustomernamefromexcel(request): return HttpResponse('html') -
Django is not returning success to html template
I have created a contact form and when the processing is done, it is returning data in the error div tag instead of success div tag. from django.shortcuts import render, redirect from django.http import HttpResponse from django.core.mail import send_mail from django.contrib import messages from django.core.mail import send_mail from .models import Contact def contact(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] contact = Contact(name=name, email=email, subject=subject, message=message) contact.save() # Send email send_mail( "From e-learning:"+subject, message, 'senderemail@gmail.com', ['receiver1@gmail.com', 'receiver2@gmail.com'], fail_silently=False ) send_mail( "Welcome to e-learning", "Thank very much for contacting us.We received your enquiry. Our team will contact you as early as possible.", 'senderemail@gmail.com', [email, 'receiver1@gmail.com'], fail_silently=False ) messages.success(request, 'Your request has been submitted, a realtor will get back to you soon') #return redirect('/listings/'+listing_id) #return redirect('/') return HttpResponse("Details are submitted") The template, I have pointed to. <form action="{% url 'contact' %}" method="POST" role="form" class="php-email-form mt-4"> {% csrf_token %} <div class="form-row"> <div class="col-md-6 form-group"> <input type="text" name="name" class="form-control" id="id_contact_name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" /> <div class="validate"></div> </div> <div class="col-md-6 form-group"> <input type="email" class="form-control" name="email" id="id_contact_email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" /> <div class="validate"></div> </div> </div> <div … -
Django migration error-Manager object has no attribute 'name'- Error on Migration
I was trying implement staff management project in DJango, I created custom user and added that one to one field in my staff model. I created manager class for Staff. But when I am trying to migrate my model it says manager object has no attribute 'name'. If I add a field name in manager this error will be disappeared. Can any one please help me why this error? class CustomModelManager(models.Manager): """ customised foam of model manager """ def __init__(self): # this can be overriden on child class self.ARG={ 'status':int, 'app_label':str, 'model_name':str, 'content_type_id':int, 'detailed':bool, 'pk':int, 'codename':str, 'name':str, 'id':int } # if any user argument having another label that model relation # will replace the smame with replacement values""" self.REPLACING_VALUES={ 'model_name':'content_type__model_name', 'content_type_id':'content_type__id', 'app_name':'content_type__app_label' , 'app_label':'content_type__app_label' } self.DEFAULT_PARAMETERS={ 'content_type__status__active':True } self.VIEW_PARAMETERS_LIST=[ ] from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from branch.models import Branch from django.contrib.auth.models import Group from common.managers.custom_manager import CustomModelManager from django.contrib.auth.models import Permission class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email … -
Keeping annotated rank when filtering Django
I have a filtered Queryset where I have annotated the rank of each object according to a specific order. When I then perform other filters like changing the order by the rank stays the same. The problem comes when perfoming a new .filter() I have a search function on the page that filters the results after the title of the objects. But when I do this the annotated rank value changes depending on how many results are in the new query instead of keeping its original value. To illustrate: This is my original query: choices_filter = Choice.objects.filter(tournament=pk).annotate (rank=RawSQL("RANK() OVER(ORDER BY winrate DESC, pickrate DESC, times_played)", [])) This returns a queryset like this: Rank Title Winrate 1...........Apple...........55% 2...........Pear............47% 3...........Banana..........44% 4...........Orange..........35% 5...........Watermelon......31% If I perform a .order_by('title') I get the expected result of: Rank Title Winrate 1...........Apple...........55% 3...........Banana..........44% 4...........Orange..........35% 2...........Pear............47% 5...........Watermelon......31% But if I instead perform a .filter(title__icontains='an') I get this: Rank Title Winrate 1...........Banana..........44% 2...........Orange..........35% Instead of the desired: Rank Title Winrate 3...........Banana..........44% 4...........Orange..........35% I am still not experienced enough with Django and python (and databases) to navigate through this on my own. It took me a while to figure out how to annotate the rank and have it working with … -
EveryTime the runserver Reload why this warning Shows up in my Terminal can anyone help please
Everytime i make changes in the code when runserver is automatically reloaded it shows the below warning. and its in all my projects. Please if anyone can suggest something it would be a great help Thanks Im using postgres as database /Users/chip/Documents/Git/test_project/cart/api/v1/serializers.py changed, reloading. Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/Users/chip/Documents/Git/apis_gifola/venv/lib/python3.8/site-packages/IPython/core/history.py", line 780, in writeout_cache self._writeout_input_cache(conn) File "/Users/chip/Documents/Git/apis_gifola/venv/lib/python3.8/site-packages/IPython/core/history.py", line 763, in _writeout_input_cache conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)", sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 123145399545856 and this is thread id 4726091200. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 28, 2020 - 05:53:02 Django version 2.2.3, using settings 'test_project.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. -
Django: within html reference foreign key from user
models.py: class Banking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) available_credits = models.PositiveIntegerField() base.html: {{ user.banking.available_credits }} Can I use the user object to reference the available_credits in the banking table? I'm using this base.html as a template which all other templates extend and ideally don't want to pass the specific instance in. I was hoping there was a way to reference it in a similar way to {{ user.username }} -
Django: Why does a migration pass a None value to a custom field in which I haven't set null=True?
This is a custom field I defined to represent a time duration because I wanted a field that I could create with a single float type (seconds) and have that same value when I access the object's attribute, but that I could render in my HTML as a string with the format hh:mm:ss. I tried with DurationField() but this doesn't work for me because it's rendered as hh:mm:ss.ffff, and I had to do too many things to get rid of the decimals. I defined this field following the example in the documentation. There were some things I didn't understand completely, but I managed to make it work initially when I wasn't passing any arguments to the field (like blank=True) and when I was only passing a constant value to this model attribute in my view, after save(commit=False) and before save(). I did this first because I hadn't written the code that calculates its value. Note that the value for this field is not to be entered by the user in a form, this is the result of a calculation that's based on user-entered data. The thing is now that, to make this calculation, I need the model instance to be … -
Add a field to the Django admin for a custom user model
I have a custom user model: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_happy = models.BooleanField(default=False) I'm referencing it within AUTH_USER_MODEL. And I've generated an admin for it based on the UserAdmin from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from .models import User @admin.register(User) class UserAdmin(DjangoUserAdmin): pass But the is_happy field doesn't appear in the user admin page. How/where do I tell this UserAdmin about additional fields that I'd like it to display? Further details Django v3.1.3 Python v3.8.5 -
How to return raw query result in django
How to return the raw query result in django. Following is my code join = Books.objects.raw({'$lookup': { 'from': 'titles', 'localField': 'title', 'foreignField': 'title', 'as': 'join_array' }}) return HttpResponse(join) -
Django Bootstrap Accordion needs double click to expand
When I click the accordion the first time nothing happens. When I click it a second time, it opens and then closes immediately! It's like the second click sends both. Here's my template: {% for category in challenges_by_category_list %} {% if category %} <h2>{{ category.title }}</h2> <div class="accordion" id="accordion{{category.title}}"> {% for challenge in category.challenge_set.all %} <div class="card"> <div class="card-header" id="heading{{challenge.id}}"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapse{{challenge.id}}" aria-expanded="true" aria-controls="collapse{{challenge.id}}"> {{ challenge.question_text }} </button> </h2> </div> <div id="collapse{{challenge.id}}" class="collapse in" aria-labelledby="heading{{challenge.id}}" data-parent="#accordion{{category.title}}"> <div class="card-body"> Anim pariatur cliche reprehenderit, enim eiusmod high </div> </div> {% endfor %} </div> {% endif %} {% endfor %} I wondered whether it's something to do with including bootstrap twice? But here's my base.html includes: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> I've also installed crispy_forms which uses bootstrap, I don't know if that's relevant. -
How do you select a random element out of list, in django template?
I have a list of links generated in my views, now i want to redirect my page to a random link in this list. Is there a way to select a random element out of the list in the django template? I don't want to redirect the view to another view where the generation happens then redirection etc because every press of the button will lead to generation...instead simply selecting a random element out of the list so it's very fast.. Couldn't hack it via google template <div class="container-fluid center"> <a class="btn waves-effect waves-light" href={{ random_link }}>Redirect me to a cute pic <i class="large material-icons left">favorite</i> <i class="large material-icons right">favorite_border</i> </a> </div> views.py reddit = praw.Reddit(client_id='L685-1uBBrLbKQ', client_secret='_Fk5nW1L2h3VRR6BVnkusMh43QQ_gg', user_agent='Shivam Anand') top_natureismetal = reddit.subreddit('natureismetal').top(limit=100) # generator only generated once for loop run nature_links = [] for post in top_natureismetal: nature_links.append(post.url) import random random_link = random.choice(nature_links) #the part i want html to do... -
How to get data of Post.user not the logged in User
I am currently working on a blog project for learning purposes, I am trying to get the total number of posts made by a specific user. In my model I have set the User who makes a Post as Author. In the Post detail page I am trying to show the total number of Posts made by this specific author but I am getting the data of the logged in User who is viewing the page. The reason for this is using self in the get context data but I am not sure how to fix it so I need some explanation on how to amend this error in code. Here is the Post Model: class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = RichTextUploadingField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') Here is the views.py: class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) num_post = Post.objects.filter(author=self.request.user).count()#<--- No. of Posts made by an author context["num_post"] = num_post #<--- No. of Posts made by a user return context My question: How to show the data of the post detail author not the logged in user Thank you