Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Following the Django documentation step by step to set static file but it keeps tell the static tag is invalid
I've followed the Django 3 documentation to set my static file on my web .And i did load static in my template , but it still keeps tell me that the static tag is invalid . im super confused and dont know wheres the problem? Have anyone face this kind of problem ? Error like this TemplateSyntaxError at / Invalid block tag on line 8: 'static'. Did you forget to register or load this tag? Heres my directory structure mblog/ |---maonsite/ |---mblog/ |---static/ |---css |---js |---images |---templates |---index.html |---product.html And heres the setting.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '^)azutlc_vkzxpw4ghw@b$+q6g)5&%lsamt)s0i*k*gdvw##@b' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'maonsite', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mblog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS=[os.path.join(BASE_DIR, "static"), '/var/www/static/',] views.py from django.shortcuts import render from django.http import HttpResponse from . models import Post # Create your views here. def homepage(request): #index.html return render(request,'index.html') def productpage(request): return … -
Is it necessary to loop over a queryset passed to a django template when there is only one record?
When I want to show a queryset passed to a template in Django, and there is only one record, is it necessary to loop? I have something like: {% for x in blobs%} {{ x.id }} {% endfor %} Which works fine. But only one record is in blobs, as it was filtered to a specific id by the view. Would it not be better than to just access {{blobs.id}} directly? If so, what is the correct way to do that? -
Calculate values for date range values based on week and year in python/django?
I've got the following values in my db: | year | week | day_1 | day_2 | day_3 | day_4 | day_5 | day_6 | day_7 | user_id | |------|------|-------|-------|-------|-------|-------|-------|-------|---------| | 2020 | 25 | 10 | 8 | 8 | 10 | 8 | 8 | 0 | 1 | | 2020 | 26 | 5 | 5 | 8 | 8 | 8 | 8 | 10 | 2 | | 2020 | 27 | 5 | 5 | 8 | 8 | 8 | 8 | 10 | 3 | Given a date range, e.g 2020-06-24 - 2020-07-03 (June 24th to July 3rd) - how can I extract the sum of the values day_1 - day_7 given the range? (day_1 = Monday and day_7 = Sunday of the given week) So, in the case above, if I want to get the sum of user_id = 1 for the range June 24 to July 3rd, it'd be day_3 + day_4 + day_5 + day_6 + day_7 = 34 Not sure how to proceed -
Django - TypeError: not enough arguments for format string
I'm trying to make a raw query on Django, here is what i tried: Summary = myTable.objects.raw("SELECT FROM_UNIXTIME (unixtime, '%Y/%m/%d') AS ndate, count(id) AS query_count FROM myTable GROUP BY ndate ORDER BY query_count DESC") The problem is that i keep getting the following error: TypeError: not enough arguments for format string What is the problem here? If i execute this query on MYSQL, it will work. Any advice is appreciated! -
Compare list values to a queryset field
I'm struggling to determine why my IF statement is failing. Any assistance is greatly appreciated. I want to compare a list array to a database field, and when I find the match, I need to retrieve the list index number for future use. The database field must match an entry in the list as the Django model specifies the field is a lookup field. the queryset for the master records is loading as expected. the Status list is being built as expected. When I do the comparison 'if val == d.stage:' it never returns as true. what am I missing? TIA # read the database records (less than 100 records) deal_set = Deal.objects.filter().order_by('stage__sort_order') # build a list of all possible status records (there are only 10 records) queryset = Status.objects.filter().order_by('sort_order') stage_list = [] for q in queryset: stage_list.append(q.stage) # loop through each master record for d in deal_set: # loop through the list of stages and compare to the stage field in the master record for idx, val in enumerate(stage_list): if val == d.stage: stage_pos = idx break -
Saving the content of div in a charfield model Django
I'm using the TinyMCE inline editor and it changes the conetents of a particular div. I am looking for a way to store those changes in a Django model once a button is pressed. -
How can I change the default Django Form name?
In order to have a better overview on which page I'm loading which form, I would like to change the name with which it is accessed in the template. By default as far as I know it is set to 'form'. In the snipped below I'm trying to load the form with 'form_inv' but that doesn't work. {% extends "dashboard/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Investment</legend> {{ form_inv|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Create</button> </div> </form> </div> {% endblock content %} The following is the Model I created and the respective view. The Model: class MoneyGroups(models.Model): title = models.CharField(max_length=100) size = models.IntegerField() interest = models.FloatField() The Django View: class MoneyCreateView(LoginRequiredMixin, CreateView): model = MoneyGroups template_name = 'dashboard/scenario_form.html' # <app>/<model>_<viewtype>.html context_object_name = 'investments' fields = ['title', 'size', 'interest'] success_url = '/dashboard/' def form_valid(self, form): form.instance.author = self.request.user #add the author to the form before it is submitted return super().form_valid(form) What parameter do I have to change/add in my model or view in order to change the name with which I can access it in the template? Thanks for your help! -
Can't pass queryset to template via context, can pass other variables
I'm having a strange issue where I can't pass a queryset to my template my view is set as: def testview(request, urlid): blob = Blob.objects.all() context = { 'blob': blob, 'urlid': urlid, } return render(request, 'testsite/viewblob.html', context) My blob model has only one record. I only passed urlid so I can confirm it is being passed to my template. My urls.py is setup to capture an id, and it works fine. In my template, it displays with {{urlid}} as should be expected. I have been completely unable to get my one blob record to show in my template. I changed the query to be .all() when the way I was filtering was not showing up, but since .all() is not working it does not seem to have been an issue with how I was filtering. I have tried looping over it {{for blobs in blob}} , displaying by itself {[blob}}, and displaying specific fields like {{ blob.id }}, nothing works. There is one record in blob, and context is passing because urlid passes and shows, so what am I missing? -
Django RF, validation of input data in view layer
I wanted to get the date or tablerequireDate argument from the POST requests, how do I achieve in the below view layer ? VIEWS.PY class Tablecreateview(generics.CreateAPIView): queryset = Tables.objects.all() serializer_class = Tableserializer def perform_create(self, serializer): request_user = self.request.user serializer.save(author=request_user) MODELS.PY class Tables(models.Model): tablerequiretime = models.TimeField() tablerequireDate = models.DateField() created = models.DateTimeField(auto_now=True) updatedat = models.DateTimeField(auto_now_add=True) foodliketoeat = models.CharField(max_length=200) totalpersons = models.PositiveIntegerField( default=0, validators=[MinValueValidator(0), MaxValueValidator(20)]) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.author.username SERIALIZERS.PY class Tableserializer(serializers.ModelSerializer): class Meta: model = Tables exclude=('author',) -
adding comment class view
models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=100) email = models.EmailField() body = models.TextField(help_text='Add a comment') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on {self.post}' forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['email', 'body'] views.py class PostDetailView(DetailView): model = Post # display comments and comment_form def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) qs = Comment.objects.filter(post=self.kwargs.get('pk'), active=True) context['comments'] = qs.order_by('-created', '-updated') context['comment_form'] = CommentForm() # adding empty form return context class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm template_name = 'blog/post_detail.html' success_url = reverse_lazy('post-detail') new_comment = None def form_valid(self, form): post = self.get_object() form.instance.post = post form.instance.name = self.request.user return super().form_valid(form) I have post and comment models. I want to add a comment form in the post detail view. I'm able to add empty form but unable to post/add comments. PostDetailView works fine but doesn't know how to get working CommentCreateView in correct way. I've just started with class-based views. Thanks in advance. -
Getting 'maximum recursion depth exceeded while calling a Python object' while building a web app in django
i'm following this tut in youtube : https://www.youtube.com/watch?v=HWg3zXWwre8&t=91s i'm trying to seperate the head.html and put it in seperate html file and then include it in the base.html of the project, and i get this error : enter image description here What do you think is the problem guys? how can i solve this? it's my first project :P Thanks!! -
Decorator for validating incoming Twilio requests
I've attempted to follow this very straight forward guide on how to prevent non-twilio requests from hitting the webhook url that I've setup for incoming twilio messages. It basically involves copying a function they've developed as a decorator and applying it to the view that handles incoming messages. https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-django-project-by-validating-incoming-twilio-requests from django.http import HttpResponse, HttpResponseForbidden from functools import wraps from twilio import twiml from twilio.request_validator import RequestValidator import os def validate_twilio_request(f): """Validates that incoming requests genuinely originated from Twilio""" @wraps(f) def decorated_function(request, *args, **kwargs): # Create an instance of the RequestValidator class validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN')) # Validate the request using its URL, POST data, # and X-TWILIO-SIGNATURE header request_valid = validator.validate( request.build_absolute_uri(), request.POST, request.META.get('HTTP_X_TWILIO_SIGNATURE', '')) # Continue processing the request if it's valid, return a 403 error if # it's not if request_valid: return f(request, *args, **kwargs) else: return HttpResponseForbidden() return decorated_function Unfortunately, immedialy after I apply the decorator to my view that handles incoming messages, I get this error. Traceback (most recent call last): File "/home/jason/lib/python3.6/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/jason/lib/python3.6/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/jason/lib/python3.6/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jason/webapps/project/jason/jasonsproject/decorators.py", line 14, in decorated_function … -
Django check constraint for datetime
I have this model: class MyModel(models.Model): creation_datetime = models.DateTimeField() expiration_datetime = models.DateTimeField() class Meta: constraints = [ CheckConstraint( check=#### ) ] I am trying to write a check constraint to ensure that expiration_dateime > creation_dateime. I am unable to find a way to do it correctly with Q objects, help is appreciated. -
Referring to Users in Django models
I'm saving a list of values for each user on my Django app, taken from a daily poll. I can't get the 'User' field responder to save properly as it always opts for the default value 'Null'. Instead of a list of values for each user, I am getting a single list in the database for all the users combined. Here is my model: class Repondez(Model): score_list = JSONField() responder = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.score_list Here is views.py: r = Repondez() r.score_list = [] global list_length def home(request): context = {} return render(request, 'rating/home.html', context) @login_required def add(request): if request.method == 'POST': selected_option = (request.POST['rating']) list_length = len(r.score_list) if selected_option == 'option1': r.score_list.append(1) elif selected_option == 'option2': r.score_list.append(2) elif selected_option == 'option3': r.score_list.append(3) elif selected_option == 'option4': r.score_list.append(4) elif selected_option == 'option5': r.score_list.append(5) else: return HttpResponse(400, 'Invalid form') r.save() return redirect(add) context = { 'r' : r, } return render(request, 'rating/add.html', context) I have tried to avoid having a default value for responder but am always asked for one during migrate. I tried a ForeignKey and ManytoManyField for the 'User' relationship as well but in each case I am getting a single, combined list for all … -
Why does the Vscode command pallet does not work
The key strike work. Menu drops down. Shows nothing. Maybe files. This continue in all projects. It also high-lights imports as if it’s not there. But the project operates just the same. I don’t know is this is a root/path issue. Showed others and asked around and No One has any ideas. This has been hurting my productivity and learning. Tried uninstalling and reinstalling through Brew. Problem persists. -
Which is the best way for web development for scientific python program
I made a cython and python based curve fitting program which uses scipy, numpy, quadpy, numba, lmfit, matplotlib using models specific to our research field. My supervisor is very happy with it and wants me to develop a web app so that we can upload it on our server and my colleagues can easily access and use it. Also, we want to make it public after some time. I have researched a bit about this and found streamlit and django are good options for this. As I am new to this and have no experience in web development, I want to ask for suggestions for this keeping in mind the requirements. What would be the best course for a beginner like me? -
django to show a newly generated html file on each run
I have a python script (A.py) that accepts users input via form and runs another python script (B.py). B.py stores html formatted results into a folder named yymmdd. The file generated by B.py is like "results_hhmmss.html", so every time B.py script is exectued a new has html file is created. As per my urls.py code below, visiting 127.0.0.1:8888 takes me to home_page. Further, once i submit form using a button in the home_page, the scripts gets executed successfuly, a result files is generated. Further, how can I render the next webpage to view the generated results_hhmmss.html file? I am not sure how I can build the urlpatters as everytime the scripts are run, the results file has a new name. from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_page), # what path or paths to add here ??? ] I also wish to see the the relative path of the file results_hhmmss.html (which is in folder yymmdd) in the address bar so i can revisit the same link directly later. Thanks heaps in advance for taking time to read this post and willingness to help. I am using python3 and … -
Apache - (104)Connection reset by peer: [client x.x.x.x:4712] AH03308: ap_proxy_transfer_between_connections: error on sock - ap_get_brigade
I have a django app deployed to elastic beanstalk: http://django-env.eba-bcvm9cxz.us-west-2.elasticbeanstalk.com/chart/ I'm following this tutorial: https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 and using architecture number 2. My relevant configuration files are the folllowing: option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: dashboard.settings PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH aws:elasticbeanstalk:container:python: WSGIPath: dashboard/wsgi.py aws:elbv2:listener:80: ListenerEnabled: 'true' Protocol: HTTP aws:elbv2:listener:5000: ListenerEnabled: 'true' Protocol: HTTP -- files: "/etc/httpd/conf.d/proxy.conf": mode: "000644" owner: root group: root content: | ProxyPass /websockets/ ws://127.0.0.1:5000/websockets/ upgrade=NONE ProxyPassReverse /websockets/ ws://127.0.0.1:5000/websockets/ I needed to add upgrade=NONE in proxy.conf, which isn't in the tutorial, but I for me I always got a 503 on the client when it was establishing the websocket. I have a daphne server listening on 5000, which is successfuly receiving the websocket request from the client, but the client never gets to receive the response from the server. On google console I get: WebSocket connection to 'ws://django-env.eba-bcvm9cxz.us-west-2.elasticbeanstalk.com/websockets/' failed: Error during WebSocket handshake: Unexpected response code: 408 Apache's logs show the following: [Sat Jun 27 11:42:11.962267 2020] [watchdog:debug] [pid 9855] mod_watchdog.c(590): AH02981: Watchdog: Created child worker thread (_proxy_hcheck_). [Sat Jun 27 11:42:11.962286 2020] [proxy:debug] [pid 9855] proxy_util.c(1940): AH00925: initializing worker ws://127.0.0.1:5000/websockets/ shared [Sat Jun 27 11:42:11.962298 2020] [proxy:debug] [pid 9855] proxy_util.c(2000): AH00927: initializing worker ws://127.0.0.1:5000/websockets/ local [Sat Jun 27 11:42:11.962319 2020] [proxy:debug] [pid 9855] proxy_util.c(2035): … -
In django when i submit profileform it gives an error: NOT NULL constraint failed: pics_profile.user_id please help me to resolve this error
enter image description here not null constraint ,here is my models.py -
Django REST framework viewset API call
I want to make an api call for a viewset.ModelViewset, how can i do this? This is my views.py from rest_framework import viewsets from .serializers import TaskSerializer from .models import Task # Create your views here. class TaskView(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer I usually make calls with like this to the back end. fetch(url, { method: 'POST', headers: { 'Content-type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify(this.state.activeItem) }).then((response) => { //Calling to fetchTasks to update the list after edit this.fetchTasks() //Setting the state back to null this.setState({ activeItem: { id: null, title: ' ', completed: false, } }) In this example its POST request, but i read inn the Djano REST Framwork docs that the viewset provides actions such as .list() and .create(), ant not .get() or .post(). I was wondering how i can make an api call from my react app to this viewset if this is the case. -
Optimise django query when fetching information form multiple models
I am new to Django and using Django 3.0.6. With the following code, I have been able to achieve the desired results and display detailed book information onto the template. However, on average, ORM makes 8 to 9 database queries to get detailed information about the book. I am looking for expert help to optimize my database queries so that I could fetch book-related information with fewer queries. I tried using select_related() and prefetch_related() but without any luck, maybe I did it improperly. Is there a scope of using Q object or union(), just my thought? How can I achieve the same results with minimum queries to the database? Please help me with detailed code, if possible. models.py class Publisher(models.Model): publisher_name = models.CharField(max_length=50) class Author(models.Model): author_name = models.CharField(max_length=50) class Booktype(models.Model): book_type = models.CharField(max_length=20) # Hard Cover, Soft Cover, Kindle Edition, Digital PDF etc. class Book(models.Model): book_title = models.TextField() slug = models.SlugField(max_length=50, unique=False) published_date = models.DateField(auto_now=False, auto_now_add=False) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) author = models.ForeignKey(Author, on_delete=models.CASCADE) book_type = models.ManyToManyField(Booktype, through='BookPrice', through_fields=('book', 'book_type')) # I created this separate model due to havy content and to keep Book model light class BookDetail(models.Model): a = models.TextField(null=True, blank=True) b = models.TextField(null=True, blank=True) c = models.TextField(null=True, blank=True) … -
django: how can update or create object models
I want to get some object from gitlab-library and afterthat I want to compare if its save before; Update data and if its new data ; Create a new I used update_or_create but its not doesnt work properly! actually Its save default value in models! how can fix it ? from call.models import Issue, Merge from django.core.management.base import BaseCommand import gitlab import json class Command(BaseCommand): help = 'Displays Merge and Issue IDs' def handle(self, *args, **kwargs): project = gitlab.Gitlab( 'https://************', private_token='**************' ) issues = project.issues.list(state='opened') merges = project.mergerequests.list(state='opened') issuesids = [] mergesids = [] for issue in issues: issuesids.append(issue.id) Issue.objects.update_or_create(issue_id=issue.id) Issue.objects.update_or_create(title=issue.title) for merge in merges: mergesids.append(merge.id) Merge.objects.update_or_create(merge_id=merge.id) Merge.objects.update_or_create(title=merge.title) dicts = { "issues": issuesids, "merges": mergesids } a = Merge.objects.update_or_create(data=dicts) for b in a: print(b) models : from django.db import models from django.contrib.postgres import fields as pgfields class Issue(models.Model): title = models.CharField(max_length=100, blank=True, null=True, default='', verbose_name=("Issue Title")) issue_id = models.PositiveIntegerField(default=0, blank=True) def __str__(self): return self.title class Merge(models.Model): title = models.CharField(max_length=100, blank=True, null=True, default='', verbose_name=("Merge Title")) merge_id = models.PositiveIntegerField(default=0, blank=True) issue_id = models.ForeignKey('Issue', on_delete=models.CASCADE, blank=True, null=True) data = pgfields.JSONField(default=dict) def __str__(self): return self.title -
Implementing notifications with Django Rest Framework jwt authentication
I have developed an android app which uses Django rest framework as backend with JWT Authentication. Now I want to add notification service to it. There are many notification service providers like firebase cloud message and azure notification centre. I need some guidance to implement this Like, this is my user profile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) is_teacher = models.BooleanField(default= False) and I only want to send a notification to the users who are logged in as teacher. -
How to display images in Django?
I have a inventory system. When I click a medicine, it shows this specific medicine's information. This page is medicine_details.html. When I open, I get all informations true but I cannot see image. When I open page in inspect there is an error: How can I fixed it?? views.py def medicine_detail(request, id): medicine = get_object_or_404(Medicine, id=id) context = { 'medicine': medicine, } return render(request, 'medicine_details.html', context) models.py class Medicine(models.Model): medicine_name = models.CharField(max_length=100) medicine_info = RichTextField(verbose_name="notes") medicine_code = models.CharField(max_length=100) medicine_qr = models.CharField(max_length=100) medicine_price = models.IntegerField() medicine_stock = models.IntegerField() medicine_image = models.ImageField(upload_to='images', null=True, blank=True) slug = models.SlugField(max_length=100, unique=True, editable=False) def get_image(self): if self.medicine_image and hasattr(self.medicine_image, 'url'): return self.medicine_image.url else: return def __str__(self): return self.medicine_name class Meta: ordering = ['medicine_name'] def get_create_url(self): return reverse('medicines:medicine_create', kwargs={'slug': self.slug}) def get_unique_slug(self): slug = slugify(self.slug.replace('ı', 'i')) unique_slug = slug counter = 1 while Medicine.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def get_absolute_url(self): return reverse('medicines:medicine_create', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = self.get_unique_slug() return super(Medicine, self).save(*args, **kwargs) medicine_details.html <div class="panel panel-primary"> <div class="panel-heading text-center"><h3>{{medicine.medicine_name}} </h3></div> <div class="panel-body"> <h4><p class="text-success">Medicine Name: <small>{{medicine.medicine_name}}</small></h4> <h4><p class="text-success">Details: <small>{{medicine.medicine_info}}</small></h4> <h4><p class="text-success">Barcode: <small>{{medicine.medicine_code}}</small></h4> <h4><p class="text-success">QR: <small>{{medicine.medicine_qr}}</small></h4> <h4><p class="text-success">Price: <small>{{medicine.medicine_price}} TL</small></h4> <h4><p class="text-success"> <small></small></h4> <img src="{{ medicine.medicine_image.url }}" alt="img"> settings.py ... … -
Django: Unused 'v_item.pk' at end of if expression
I'm trying to hide a button if the ID already exist in other table. I have a Confirm button in my template that i use to confirm orders and it save the confirmed orders in a table called (ConfirmOrder). So i want if order is already confirmed or the id of that order already exist in ConfirmOrder table the confirm button is disabled/hidden so that i cannot confirm it again. I tried to use templatetags i get this error (Unused 'v_item.pk' at end of if expression) Model class ConfirmOrder(models.Model): order_no = models.ForeignKey(OrderDetail, related_name='confirmorders', on_delete = models.SET_NULL, null=True) product = models.ForeignKey(StoreStock, null=True, blank=True, on_delete = models.SET_NULL) quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) buying_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) amount = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) confirm_note = models.CharField(max_length = 50, blank=True) is_active = models.IntegerField(default=1) Template tag from django import template from ..models import ConfirmOrder register = template.Library() @register.simple_tag def check_item_already_exists(request, pk): return ConfirmOrder.objects.filter(id=pk, is_active=1).exists() Templates {% for v_item in viewitem %} <tr> <td>{{ forloop.counter }}</td> <td>{{ v_item.order_no.location }}</td> <td>{{ v_item.order_no.order_date }}</td> <td>{{ v_item.order_no.supplier }}</td> <td>{{ v_item.order_no.order_number }}</td> <td>{{ v_item.order_no.pay_ref }}</td> <td>{{ v_item.product }}</td> <td>{{ v_item.quantity }}</td> <td>{{ v_item.buying_price }}</td> <td>{{ v_item.amount }}</td> <td> …