Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a searchable text field to select a foreign key item in Django form?
I have a filter form as you can see in the screenshot. I would like to add a searchable field(in the red area) so users can filter the campaign naming tool object instead of scrolling. Any help is appreciated. My filter class class UserInsertionOrderFilter(django_filters.FilterSet): start_date = django_filters.DateFilter(widget=DateInput) end_date = django_filters.DateFilter(widget=DateInput) class Meta: model = UserInsertionOrder fields = [ 'campaign_naming_tool', 'start_date', 'end_date' ] My filter form -
Django request for CAC (common access card)
I am currently running my Django application on an Apache v2.4.5.2 server. When the user hits initial page (i.e. www.djangoApp.com) they are prompted to insert their CAC and PIN. Once complete, the PIN entry pop-up goes away and the user is directed to the landing page. The issue I'm having is figuring out how to identify the user based on the HTTP response received from the external source (GCDS). In the server logs, I can see the request information, but I am unsure how to view that request in Django views. I tried to comment out all middleware so that the request would make it through, but that doesn't work. Does Apache block certain HTTP Requests? Is there somewhere I need to allow external requests? The only request I'm getting is: {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'REQUEST_URI': '/', 'SCRIPT_NAME': '', 'PATH_INFO': '/', 'PATH_TRANSLATED': '\DjangoWebProject1\\wsgi.py\\', 'HTTP_HOST': 'glen', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_SEC_CH_UA': '" Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"', 'HTTP_SEC_CH_UA_MOBILE': '?0', 'HTTP_SEC_CH_UA_PLATFORM': '"Windows"', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'HTTP_SEC_FETCH_SITE': 'none', 'HTTP_SEC_FETCH_MODE': 'navigate', 'HTTP_SEC_FETCH_USER': '?1', 'HTTP_SEC_FETCH_DEST': 'document', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.9', 'HTTP_COOKIE': 'csrftoken=Nd3ggEPk0vqYJwZKOVZZoZtUqZWXs155Y6V1q', 'HTTP_X_FORWARDED_FOR': '128.202.106.24', 'HTTP_X_FORWARDED_HOST': 'glen', 'HTTP_X_FORWARDED_SERVER': … -
Django kubernetes error error converting YAML to JSON: yaml: line 11: mapping values are not allowed in this context
im using Django and kubernetes to create a website and when i run helm upgrade --install --dry-run --debug django-test ./helm/django-website there seems to be a problem with deploypment.yaml but i cant seem to find the issue ive tried multiple methods from forms and used yaml checkers but i cannot fix it i dont know why it has a problem to begin with because the program generated it all i added was command: ["make", "start-server"] on line 36 here is the code for deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: {{ include "django-website.fullname" . }} labels: {{ include "django-website.labels" . | nindent 4 }} spec: {{ if not .Values.autoscaling.enabled }} replicas: {{ .Values.replicaCount }} {{- end }} selector: matchLabels: {{- include "django-website.selectorLabels" . | nindent 6 }} template: metadata: {{- with .Values.podAnnotations }} annotations: {{- toYaml . | nindent 8 }} {{- end }} labels: {{- include "django-website.selectorLabels" . | nindent 8 }} spec: {{- with .Values.imagePullSecrets }} imagePullSecrets: {{- toYaml . | nindent 8 }} {{- end }} serviceAccountName: {{ include "django-website.serviceAccountName" . }} securityContext: {{- toYaml .Values.podSecurityContext | nindent 8 }} containers: - name: {{ .Chart.Name }} securityContext: {{- toYaml .Values.securityContext | nindent 12 }} image: "{{ .Values.image.repository }}:{{ … -
How to call function from views.py to models.py?
Problem I'm new in Django, I have a function to retrieve foreign key object in views.py and I want to call this function to models.py, is there any way to do this? views.py def get_fk(request): if request.method == 'POST': category = itemCategory.objects.get(pk=request.POST.get('idItemCat')) return category models.py class MyUser(AbstractUser): pass class ItemCategory(models.Model): idItemCat = models.CharField(primary_key=True max_length=5) nameCategory = models.CharField(max_length=150) class ItemCode(models.Model): idItemCode = models.CharField(primary_key=True, editable=False, max_length=20) idItemCat = models.ForeignKey(ItemCategory, on_delete=models.DO_NOTHING) What I've tried To import a function usually in django like this from .views import get_fk, but every time I did that it doesn't work and getting this error, it said that my custom user has not been installed. Traceback (most recent call last): File "D:\VS_Code\.venv\lib\site-packages\django\contrib\auth\__init__.py", line 160, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "D:\VS_Code\.venv\lib\site-packages\django\apps\registry.py", line 211, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "D:\VS_Code\.venv\lib\site-packages\django\apps\config.py", line 270, in get_model raise LookupError( LookupError: App 'aset_app' doesn't have a 'MyUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Zeidan\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\Zeidan\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "D:\VS_Code\.venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\VS_Code\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "D:\VS_Code\.venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\VS_Code\.venv\lib\site-packages\django\core\management\__init__.py", … -
Django - (admin.E015) The value of 'exclude' contains duplicate field(s)
I have the following Models: class Step(models.Model): start_time = models.TimeField() time = models.IntegerField() schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE) class Schedule(models.Model): identifier = models.CharField(max_length=10) name = models.CharField(max_length=100) steps = models.ManyToManyField('manager.Step', related_name='steps') These are registered to django-admin as follows: @admin.register(Schedule) class ScheduleAdmin(admin.ModelAdmin): list_display = ['identifier', 'name'] @admin.register(Step) class StepAdmin(admin.ModelAdmin): list_display = ['start_time', 'time', 'schedule'] exclude = list('schedule') However when running the server I get the following error: ERRORS: <class 'manager.admin.StepAdmin'>: (admin.E015) The value of 'exclude' contains duplicate field(s). How can I resolve this issue? I am unfamiliar with how Two way binding in Django is supposed to work? -
How to map out With python Django Management CMD [duplicate]
The is active flag and blacklist flag have the same intention although both are available. Since with is active filtering is possible and it is seen in the overview all blacklist should be mapped to is active. -
Getting Realtime data and parsing it locally in Django Rest Framework
I want to build a Django REST API that gets crypto pricing data from Coin Market Cap and shows it on GET localhost according to my own parameters. There are a few questions, however, Coin market cap uses API auth keys, where does it go? Where do I put it? In What headers? Do I really need models if I am getting a predefined URL that already displays what I want? -
getting "This field is required" message. while uploading image
i don't have any problem in submiting char fields but when i put an image field i get this message -> "This field is required" while im filling the form . models.py : class Home(models.Model): image = models.ImageField(upload_to='image') titr = models.CharField(max_length=200) description = models.TextField() created = models.DateField(auto_now_add = True) updated = models.DateField(auto_now = True) class Meta: ordering = ['created'] def __str__(self): return str(self.titr) views.py : def craethome(request): form = HomeForm() if request.method == "POST": form = HomeForm(request.POST,request.FILES) if form.is_valid(): form.save() return redirect("home") return render(request, 'home/home_form.html', {"form":form}) forms.py : from django.forms import ModelForm from .models import Home class HomeForm(ModelForm): class Meta(): model = Home fields = "__all__" my html file: {% extends 'main.html' %} {% block content %} <img src="{{home.image.url}}"> <h1>{{home.titr}}</h1> <p>{{home.description}}</p> {% endblock content %} -
Why does HTML/Django template execute code out of order?
This html template from my online class executes as intended, but why? It seems like it is executing out of order: It calls my python form class using Django's syntax {{form}} to inject the blank fields for the user to fill out (name, email, textbox) The user can enter and hit the "Submit" button but then (confusingly) is that it seems the {{form}} class is called again with the entry information as it then successfully prints out user input to the terminal. Why is this? html in templates.py <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <h1>fill out the form</h1> <div class="container"> <form method="POST"> {{form}} {% csrf_token %} <input type="submit" class="btn btn-primary" value="submitme"> </form> </div> </body> </html> Form class in views.py def form_name_view(request): form = forms.FormName() if request.method == "POST": form = forms.FormName(request.POST) if form.is_valid(): print("VALIDATION SUCCESS") print("NAME: " + form.cleaned_data['name']) print("EMAIL: " + form.cleaned_data['email']) print("TEXT: " + form.cleaned_data['text']) return render(request, 'first_app/form_page.html', {'form' : form}) Supplemental: the url that uses the html template and my forms class from django.urls import path from first_app import views urlpatterns = [path('formpg', views.form_name_view, name = 'formpg')] -
How to change CSV value into a DateTime object
I am trying to upload data from a CSV into a Django model. On the CSV there is a date field and the values look like this: 2020-11-11 14:06:25+00:00 Which brings up this error: '“Deadline” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.' I am saving the value into a DateTimeField. How would I convert the CSV data into a DateTime object? I appreciate your help on this. Thanks! -
Google Cloud Run correctly running continuous deployment to github, but not updating when deployed
I've set up a Google Cloud Run with continuous deployment to a github, and it redeploys every time there's a push to the main (what I what), but when I go to check the site, it hasn't updated the HTML I've been testing with. I've tested it on my local machine, and it's updating the code when I run the Django server, so I'm guessing it's something with my cloudbuild.yml? There was another post I tried to mimic, but it didn't take. Any advice would be very helpful! Thank you! cloudbuild.yml: steps: # Build the container image - name: 'gcr.io/cloud-builders/docker' args: ['build', '-t', 'gcr.io/${PROJECT_ID}/exeplore:$SHORT_SHA', './ExePlore'] # Push the image to Container Registry - name: 'gcr.io/cloud-builders/docker' args: ['push', 'gcr.io/${PROJECT_ID}/exeplore'] # Deploy image to Cloud Run - name: 'gcr.io/cloud-builders/gcloud' args: - 'run' - 'deploy' - 'exeplore' - '--image' - 'gcr.io/${PROJECT_ID}/exeplore' - '--region' - 'europe-west2' - '--platform' - 'managed' # Deploy container image to Cloud Run - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk' entrypoint: gcloud args: ['run', 'deploy', 'exeplore', '--image', 'gcr.io/${PROJECT_ID}/exeplore', '--region', 'europe-west2', '--platform', 'managed'] images: - gcr.io/${PROJECT_ID}/exeplore Here are the variables for GCR -
How to map out via Django Management command [duplicate]
The is active flag and blacklist flag have the same intention although both are available. Since with is active filtering is possible and it is seen in the overview all blacklist should be mapped to is active. def handle(self, *args, **options): roses.objects.filter(active=False).update(blacklist=True) -
Annotate dict data from related field Django
I have a model MyModel that contains a JSONField named calculo in MySQL and I want to annotate the value of premio to perform aggregated sum. How can I make this work? class MyModel(models.Model): ... calculo = JSONField(blank=True, null=True) ... I have tried this but got an empty dict. qs = MyModel.annotate(value=F('calculo__premio')) Fairfax field: '{"sc_ha": 2.77, "premio": 27735.84, "status": "1"}' -
Page not re-rendering when receiving post request from jquery to django backend
Jquery on HTML page in script tags $("input[type='radio']").click(function(){ var radioValue = $("input[name='filter']:checked").val(); if(radioValue){ var CSRFtoken = $('input[name=csrfmiddlewaretoken]').val(); jQuery.post("/", {filter:radioValue, csrfmiddlewaretoken: CSRFtoken }); } }); }); django view (python) def homepage(request): context = {} if request.POST: filter = request.POST.get('filter') filteredarticles = list(Article.objects.all().filter(is_draft = False, topic =filter)) context['features'] = filteredarticles print(filteredarticles) return render(request, 'homepage.html', context=context) else: allarticles = list(Article.objects.all().filter(is_draft=False)) FEATUREDQUANTITY = 7 featuredArticles = [] for i in range(FEATUREDQUANTITY): k = random.randint(0, (len(allarticles)-1)) featuredArticles.append(allarticles[k]) allarticles.pop(k) context['features'] = featuredArticles print('seen') return render(request, 'homepage.html', context=context) The thought process is as follows: Using radio buttons in HTML. Jquery listening for click actions. Sends post request to view function containing the selected radio {name:value} and the CSRF_token information. The view receives the post request and processes it through the If condition and re-renders the page with the appropriate data. Everything is working, the post request is received, the data inside filteredarticles is changing, but the website itself isn't re rendering with the new context values I am passing in. Any help would be appreicated edit: Is it because I'm not passing a success callback function in my jquery.post? -
Django - Restrict API access by geolocation
We have model and view: from django.db import models from rest_framework.decorators import api_view from rest_framework.response import Response class Store(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=100) @api_view(['get']) def get_checklist_by_store_id(request, store_id): # request.user should has access to this view only when request.user inside the store with id=store_id return Response() User can get checklist by store_id. And we need to restrict access to view get_checklist_by_store_id and allow user to have access only when user is inside the store with id=store_id. First what I thought about was to add to model Store field with geo coordinates. Then on frontend implement geolocation API. When user is trying to get access to the view to ask him turn on geolocation and at last send request with his geo coordinates. And in the view compare user's geo coordinates and store geo coordinates (with some distance error). Maybe there is another approach to solve this kind of problem? -
FullCalendar not displaying correctly in django
current Fullcalendar display Hey so I'm working with FullCalendar and I'm trying to display the calendar but it ends up displaying the way it is in the picture attached to this post. I'm not sure why it displays like this and I followed the instructions on their scripts tag page but no luck. Does anyone know why and how to fix this issue? Here's the code I'm using for this {% extends 'apisapp/base.html' %} {% load static %} {% block content %} {% block extra_css %} <style> .btn-success { background-color:#7AAF4F; } .btn { font-weight: bold; } </style> </link rel="stylesheet" href="{% static 'fullcalendar/lib/main.css' %}"> {% endblock extra_css%} <body style="background-color: #2B2B2B; color: white;"> <div class="card" style="background-color: #2B2B2B; color: white;"> <div id="calendar" class="container" ></div> </div> </body> {% block extrajs %} <script src="{% static 'fullcalendar/lib/main.js' %}"></script> <script> document.addEventListener('DOMContentLoaded', function() { var calendarUI = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarUI, { }); calendar.render(); }); </script> {% endblock extrajs%} {% endblock %} -
4 by 4 square grid for 52 random images using Django
I want to create a 4 by 4 grid of about 52 images that can randomly appear in each square of the grid. I am trying to use Django since its what im into right, but if Javascript is better than I can use it. Any suggestions to get started on this project is what i am looking for -
show products in a specific category in html
i have a products and categories Model already implemented in models.py in a django application. In an html template i want to show products of a single category that i want to define in html, like category == example or something similar. class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, related_name='products', on_delete=models.CASCADE) title = models.CharField(max_length=255) this is the models.py snippet, below is the html snippet that i am trying to use {% for product in category.products.all %} I am already using this snippet to show products on category page, the category is going to be defined using the category url, but in this case i want to do that. -
send mail contact form with django
I don't understand, when I do the message test nothing happens, and in the terminal we put dis page not found help me to solve the problem DEFAULT_FORM_EMAIL="ouesergegedeon225@gmail.com" EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'ouesergegedeon225@gmail.com' EMAIL_HOST_PASSWORD = '@@@@@@@@@@' EMAIL_USE_TLS = 'True' EMAIL_USE_SSL = 'False' def send_mail(request): if request.method=="POST": name = request.POST.get['name'] subject = request.POST.get['subject'] email = request.POST.get['email_address'] message = request.POST.get['message'] send_mail( name, subject, email, message, 'ouesergegedeon225@mail.com', ['gedeonachat@mail.com'], fail_silently=False, ) message.info (request, 'Votre message a été envoyé') return render(request, 'contact.html') path('send_mail/', views.send_mail, name="send_mail"), <div class="col-lg-5 offset-lg-6 col-md-12"> <div class="section-title v2"> <h2>Écrivez-nous par formulaire</h2> </div> <form action="send_mail" method="post" id="contact_form"> {% csrf_token %} <div class="form-control-wrap"> <div id="message" class="alert alert-danger alert-dismissible fade"></div> <div class="form-group"> <input type="text" class="form-control" id="fname" placeholder="Nom et prénom" name="fname"> </div> <div class="form-group"> <input type="text" class="form-control" id="subject" placeholder="Le sujet" name="subject"> </div> <div class="form-group"> <input type="email" class="form-control" id="email_address" placeholder="E-mail" name="email"> </div> <div class="form-group"> <textarea class="form-control" rows="8" name="message" id="message" placeholder="message"></textarea> </div> <div class="form-group"> <button type="submit" class="btn v7" >Envoyer le message</button> </div> </div> </form> </div> I don't understand, when I do the message test nothing happens, and in the terminal we put dis page not found help me to solve the problem -
Django not responding back to react
I am making a request from React frontend to a view in Django (rest framework). The view in Django will make a request to another server (Google-Ads API), the request works fine and I get the data perfectly. The post-processing of that data also works fine but Django gets stuck after that means It will not run return Response(data). Django view sample code def get(self,request): data = google_api_request(credentials) data = preprocess(data) print("end") # code stops here return Response(data,status) # this will not be executed React sample code: axiosInstance.get("url").then( (result) => { if (result.status == 200) { console.log("sucess") } } ).catch(error => { throw error; }) } When I paste the "url" directly in my browser it works and returns the Response, but only when I run it from react it does not respond. When I commented google_api_request() code for debugging It returns the Response. Note: There is no errors message in the console or Django and my CORS setting is correct as other function works fine. -
Ordering collisions when cloning Django Model
I am running into issues whenever I clone a users grocery list with a m2m relationship on groceryitems. def make_clone_for_update(self, user): clone = super().make_clone_for_update(user) for b in self.grocerylist_set.all(): b.pk = None b.user_id = clone.uuid b.order = self.get_max_default("order") b.save() def get_max_default(self, field): try: max = ( self.__class__.objects.all().aggregate(Max(field))[f"{field}__max"] + 1 ) except TypeError: max = 1 return max After a clone if I check the database I will have something that will have all of the food items cloned but sometimes will have duplicate order values. IE we will order values that look like Apple 11 Pear 11 Orange 12 Granola 12 Yogurt 13 In django admin I use adminsortable2 which has a strong suggestion to not use a unique constraint on the ordering field. I have also tried not using the get max default but instead just cloning the exact order field but that results in the same duplicating issue (But a lower order number). Is there any way to guarantee these ordering fields to be unique? -
Creating a second List in the Admin class , Django
'class BookingAdmin(admin.ModelAdmin): list_diplay=('id','title', 'roomsize', 'hostel', 'features','price','status' list_editable=('status',) the above code doesnt run, however without the second list(list_editable) as shwon below the code runs perfectly 'class BookingAdmin(admin.ModelAdmin): list_diplay=('id','title', 'roomsize', 'hostel', 'features','price','status')' the error <class 'main.admin.BookingAdmin'>: (admin.E121) The value of 'list_editable[0]' refers to 'status', which is not a field of 'main.Booking'. -
How to increase quantity of item in cart in Django?
My add-to-cart views. Hello everyone, I'm completely new to Django and I tried to create a simple eCommerce web application. I tried to create a logic that increases the item that is available in the cart, but I don't why the item in the cart is not working. Maybe there is an error in logic can someone help. def add_cart(request, product_id): current_user = request.user #Getting the product id product = Product.objects.get(id=product_id) #User is authenticated or not if current_user.is_authenticated: if request.method == 'POST': for item in request.POST: key = item value = request.POST[key] is_cart_item_exists = CartItem.objects.filter(product=product, user=current_user).exists() if is_cart_item_exists: cart_item = CartItem.objects.filter(product=product, user=current_user) id = [] for item in cart_item: id.append(item.id) else: cart_item = CartItem.objects.create( product = product, quantity = 1, user = current_user, ) cart_item.save() return redirect('cart') #User is not authenticated else: if request.method == 'POST': for item in request.POST: key = item value = request.POST[key] try: #Get the cart using cart id cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() is_cart_item_exists = CartItem.objects.filter(product=product, cart=cart).exists() if is_cart_item_exists: cart_item = CartItem.objects.filter(product=product, cart=cart) id = [] for item in cart_item: id.append(item.id) else: item = CartItem.objects.create(product=product, quantity=1, cart=cart) #create new cart item item.save() else: cart_item = CartItem.objects.create( product … -
Multi Level Template Inheritance using Jinja
I am working on a multilevel template inheritance using jinja. datasource.html and event1.html is rendering correctly but event2.html and event3.html are not rendering. when I click on Event 2 and Event 3 links, I am having the page of event1.html. Nothing happens when I click Event 2 and Event 3 links. Is it due to any mistake i done in inheriting or something else. Is there any way to solve this layout.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <header> </header> <section> {% block content %} {% endblock %} </body> </html> datasource.html {% extends 'layout.html' %} {% block content %} <li> <a href="#tab1">Event 1</a></li> <li> <a href="#tab2">Event 2</a></li> <li> <a href="#tab3">Event 3</a></li> <div> {% block content1 %} {% endblock %} </div> {% endblock %} event1.html {% extends 'datasource.html' %} {% block content1 %} <div> <p> this is event 1 </p> </div> {% endblock %} event2.html {% extends 'datasource.html' %} {% block content1 %} <div> <p> this is event 2 </p> </div> {% endblock %} event3.html {% extends 'datasource.html' %} {% block content1 %} <div> <p> this is event 3 </p> </div> {% endblock %} -
Reverse for 'author' with arguments '('',)' not found. 1 pattern(s) tried: ['blogapp/author/(?P<pk>[^/]+)/\\Z'
while running http://127.0.0.1:8000/blogapp/blog/ , in django 4.0, i got error reverse for... not found and this error occurs when i add (post.author.id) in href which is in template mentioned line 15 if require more information please comment below views.py def authorview(request,pk): user=User.objects.get(id=pk) return render(request,'blogapp/authorview.html',{'user':user}) In template C:\Users\SHAFQUET NAGHMI\blog\blogapp\templates\blogapp\blogretrieve.html, error at line 15 templates {% load static %} {% block content %} <h1>Blog </h1> <link rel="stylesheet" href="{% static 'blogapp/blogretrieve.css' %}"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> {% for post in q %} <div class="jumbotron jumbotron-fluid"> <div class="container"> <h2 class="display-1">{{post.title}} </h2><br> <p class="display-2">{{post.Newpost}}</p> <a href="{% url 'blogapp:author' post.author.id %}">{{post.author}}</a <!-- line 15 --> <small class="display-3">{{post.created_date}}</small> </div> </div> {% endfor %} app_name='blogapp' urlpatterns=[ path('',views.home,name='home'), path('createblog/',views.blogview,name='blogview'), path('blog/',views.blogretrieve,name='blog'), path('signup/',views.signupview,name='signup'), path('login/',views.loginview,name='login'), path('logout/',views.logoutview,name='logout'), path('author/<str:pk>/',views.authorview,name='author'), ]