Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Assigning a datetime object as the url parameter
I want to give the value of Datetime type to url as parameter using date filter. My url must be such: /account/detail-of-cash-flow/2020-8-10 This command: {{item.date_field|date:'Y-m-d'}} = '2020-8-10'. But, not working when i this commands implement to template url. template.html {% for item in cash_flow_data %} <tr class='clickable-row' data-href="{% url 'account:detail_of_cash_flow' item.date_field|date:'Y-m-d' %}"> <td>{{ item.date_field }}</td> <td>{{ item.EUR }}</td> <td>{{ item.USD }}</td> <td>{{ item.GBP }}</td> <td>{{ item.TRY }}</td> </tr> {% endfor %} urls.py app_name = "account" urlpatterns = [ path('daily-cash-flow/', views.daily_cash_flow, name = "daily_cash_flow"), path('detail-of-cash-flow/<slug:slug>/', views.detail_of_cash_flow, name = "detail_of_cash_flow") ] I hope I was able to explain my problem. -
Batch loading with Pygrametl
right now i'm using a fact table that insert in to the database one row at a time using pygrametl like the two snippets below: self.targetconnection = Etl_Common.get_database_connection(settings.DATAMART_DATABASE) self.fact_table = FactTable( name='fct_efficency', keyrefs=( 'key', ), measures=( 'measure_1' 'measure_2' ), targetconnection=self.targetconnection, ) def insert_measure_data( self, key, measure_1, measure_2, ): row_dict = { 'key': key, 'measure_1': measure_1, 'measure_2': measure_2, } try: self.fact_table.insert(row_dict) except Exception as exc: logger.error('got exception {}'.format(exc)) The problem with this solution obviusly is that if i try to insert lots of rows it takes ages to put all data into the database. Looking at the pygrametl documentation i found a very fitting solution for my problem : BatchFactTables. the problem is that following the documentation i couldn't find an example to follow regarding the insertion of multiple lines togheter... is there any guide/snippet i could use as a guide for my problem? many thanks -
django admin and models
enter image description here Hello Guys I hope all of you are doing great,I have a problem in django3,I have been given a problem and I have to solve it ,I have tried it but not able to solve this,see the image I have given link, <----question starts here This list of help1, help2,... gets stored in a database table. You could do a first version of models.py and enable the admin interface for it. ----->question ends here Can anyone give me a idea?or how to do it or in more simpler words?any ideas or suggestions is appreciated -
Is possible to save a queryset in db in django?
I need to save the result of this query: foo = WordCount.objects.filter(lesson__course=course).values('lesson__course', 'word').annotate(totWords=Sum('count')) which results in a queryset consisting of 'word', 'course' and 'totWords' I have a model with those fields and i need to save foo in it. It si possible only with a for loop or there is a clever way? -
GET IMAGE FIELD NOT ASSOCIATED TO A MODEL IN DJANGO REST FRAMEWORK
I have stored some cover images on my server. These files are not uploaded by the user and I want to pass them through REST API endpoints without relate the view/serializer/ImageField to a specific model. Here is my serielizer: class TagSerializer(serializers.Serializer): tag = serializers.CharField() updated_at=serializers.DateTimeField(format="%d-%m-%Y %H:%M:%S") image=serializers.ImageField() And this is my APIVIEW: class TagAPIView(APIView): def get(self, request, *args, **kwargs): tags=Tag.objects.filter(level=3) qs = [] for t in tags: image=settings.MEDIA_ROOT+'/tags/'+t.tag_id+'.png' (???????) qs.append({'tag':t.tag_title, 'updated_at': t.updated_at,'image':image}) results = TagSerializer(qs, many=True).data return Response(results) I've stored correctly my png files in a "tags" folder. I would like to have an output like this one: [ { "tag": "tag 1", "updated_at": 06/10/2020, "image": "http://127.0.0.1:8000/media/tags/tag_1_id.png" }, { "tag": "tag 2", "updated_at": 04/10/2020, "image": "http://127.0.0.1:8000/media/tags/tag_2_id.png" } ] Thanks a lot for your help! I love this community <3 -
Cannot log in to admin site with superuser account, which was created with console // Django
I have custom user model. After creating superuser in console I can't log in this account. Django says "Invalid username or password". But username and password are valid. I tried to fix this problem with next solution (Click), but it hadn't helped me. My models.py: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, username, password, **extra_fields): if not email: raise ValueError('Email required') email = self.normalize_email(email) user = self.model( email=email, username=username, is_active=True, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, username, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, username, password, **extra_fields) def create_superuser(self, email, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True') return self._create_user(email, username, password, **extra_fields) My settings.py: 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.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend', ) AUTH_USER_MODEL = "backend.User" -
Can't push my Django Application to Heroku Keep getting KeyError and No modulenotfounderror
I am trying to deploy my Django app on heroku but keep getting several errors. I have tried every solution here and still haven't figured out the issue. This is my first time deploying and app so please help. remote: Created wheel for psycopg2: filename=psycopg2-2.8.6-cp38-cp38-linux_x86_64.whl size=484087 sha256=7fd888a521a172ddbf2250127088186479f5314fed7eda847376249ff36b35aa remote: Stored in directory: /tmp/pip-ephem-wheel-cache-r32vyema/wheels/70/5e/69/8a020d78c09043156a7df0b64529e460fbd922ca065c4b795c remote: Successfully built psycopg2 remote: Installing collected packages: dj-database-url, asgiref, pytz, sqlparse, Django, gunicorn, idna, Pillow, psycopg2, soupsieve, whitenoise remote: Successfully installed Django-3.1 Pillow-7.1.2 asgiref-3.2.10 dj-database-url-0.5.0 gunicorn-20.0.4 idna-2.8 psycopg2-2.8.6 pytz-2019.1 soupsieve-2.0.1 sqlparse-0.3.0 whitenoise-5.2.0 remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 224, in fetch_command remote: app_name = commands[subcommand] remote: KeyError: 'collectstatic' remote: During handling of the above exception, another exception occurred: remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 231, in fetch_command remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 177, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, … -
Get id of an looped in html element
{% for product in products %} ... <form class="form-inline"> <div class="input-group"> <input type="hidden" name="productId" id="productId" value="{{product.id}}"> <input type="text" class="form-control" name="productQuantity" id="productQuantity" style="width: 40px; height: 40px;" placeholder="1"> <div class="input-group-append"> <button type='button' name="addToCart" id="addToCart" value="+" class="btn btnother"><i class="fas fa-plus fa-sm" style="color: white;"></i></button> </div> </div> </form> ... {% endfor %} This is a simplified code! So I have an e-commerce Django website. On the main page I represent cards of different products with possibility of adding them to cart. Every time someone adds item to a cart, I want to only update cart image in header. So I want to use AJAX to pass productId and productQuantity to my views.py. Here is my JS: $(document).ready(function(){ $('form').click(function() { var productId = $('#productId').val(); var productQuantity = $('#productQuantity').val(); if (Number.isInteger(Number(productQuantity))){ productQuantity = productQuantity; } else { productQuantity = 1; } $.ajax({ url: 'update', type: 'post', cache: false, data: { 'productId' : productId, 'productQuantity' : productQuantity } }); }); }); However, when I add to cart, the productId being printed is the same for all products. I think it is because after the for loop it stores only the last productId What would be a way to get the id of every individual element? -
AJAX GET request is not showing an error in console but also not firing
I have a bit of an issue I'm hoping some fresh eyes can help with. I have an ajax get request that is supposed to pull some data from my database via Django views class and then display it on an html page. After doing a bit of debugging I've gotten it to the point where it is not throwing an error, however it is also not providing any data now. I'm wondering if someone could have a look and offer some feedback? Here is the AJAX request $(document).ready(function(){ console.log('Document Ready') $.ajax({ type: "GET", url : '/electra/playlist/', dataType: "json", //contentType: "application/json", data: { 'venue': 'venue', 'list': 'list', }, success: function(data){ $("#cafe-playlist").html(data); console.log(data) }, failure: function(errMsg) { alert(errMsg); } }); }); Here is the urls: urlpatterns = [ [...] path('electra/playlist', views.user_playlist.as_view()), Here is the views.py class user_playlist(ListView): template_name = 'testingland/dashboard.html' context_object_name = 'playlist' model = UserVenue def get_queryset(self): venue_name = self.request.GET.get('venue', None) list_name = self.request.GET.get('list', None) return UserList.objects.all() Here is the html template <body> {% block content %} <div class="container-fluid" style="padding:15px"> <!--location --> <div class="row"> <div class="col-sm-3" id="playlist"><p>Lists</p> <ul id = "cafe-playlist"> {% for item in playlist %} <li> <div> <h6 class="playlist-name">{{ item.list }}</h6> </div> </li> </div> {% endfor %} {% … -
Django: Duplicated logic between properties and queryset annotations
When I want to define my business logic, I'm struggling finding the right way to do this, because I often both need a property AND a custom queryset to get the same info. In the end, the logic is duplicated. Let me explain... First, after defining my class, I naturally start writing a simple property for data I need: class PickupTimeSlot(models.Model): @property def nb_bookings(self) -> int: """ How many times this time slot is booked? """ return self.order_set.validated().count() Then, I quickly realise that calling this property while dealing with many objects in a queryset will lead to duplicated queries and will kill performance (even if I use prefetching, because filtering is called again). So I solve the problem writing a custom queryset with annotation: class PickupTimeSlotQuerySet(query.QuerySet): def add_nb_bookings_data(self): return self.annotate(db_nb_bookings=Count('order', filter=Q(order__status=Order.VALIDATED))) The issue And then, I end up with 2 problems: I have the same business logic ("how to find the number of bookings") written twice, that could lead to functional errors. I need to find two different attribute names to avoid conflicts, because obviously, setting nb_bookings for both the property and the annotation don't work. This forces me, when using my object, to think about how the data is … -
TypeError: Field 'id' expected a number but got (()
Hello i need ur help :) Im at this Django project in school. I replaced the auth_user table with the AbstractBaseUser Class and created a new class called UserLogin one. So creating a superuser works fine, but creating the user with the signup page does not work I spent now about 10hours at that error, trying to solve. Hope u can help me Thank u If u need more information, please write it This is the whole error message TypeError: Field 'id' expected a number but got ((), {'email': 'admin@adminator.ch', 'first_name': 'ksfd', 'last_name': 'dfsg', 'location': 'Bern', 'date_of_birth': datetime.datetime(2020, 9, 29, 0, 0, tzinfo=<UTC>), 'plz': 4589, 'license_plate_number': 80291, 'license_plate_char': 'BE', 'country': 'CH', 'address': 'adminstrasse', 'phone_number': '0453268', 'raw_password': 'Balmistar45!', 'is_staff': False, 'is_superuser': False}). [08/Oct/2020 09:03:08] "POST /accounts/signup HTTP/1.1" 500 176373 This is my model: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.utils import timezone class UserAccountManager(BaseUserManager): 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 must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def … -
How to get Option field value in Request in Django?
I am trying to update my foem, and I have Country value in dropdown and I want to get this value in request, so that i can update my form using this value in request, Please check my code and let me know where I am mistaking. Here is my test.html file... <select name='country'> <option>Select One</option> {% for countries in country %} <option value="{{country.id}}" {% if countries.id == datas.country_id %}selected{% endif %}>{{countries.country}}</option> {% endfor %} </select> here is my views.py file... datas = MyModelName.objects.get(pk=id) if request.method == "POST" datas.country = request.POST.get('country') datas.save() it's not selecting the country, it's giving me error, Please guide me how i can solve this issue. -
How to group by using Django query
I have next data in the database: Start 08:00:00 , Stop 13:00:00, reference: 0a220a79-83fc-4957-a8c2-7f8f5414abd1, type: workplace Start 08:00:00 , Stop 13:00:00, reference: 0a220a79-83fc-4957-a8c2-7f8f5414abd1, type: showroom Start 09:00:00 , Stop 14:00:00, reference: 54f7beb6-75b5-4489-ba62-99f750693a1f, type: workplace Start 09:00:00 , Stop 14:00:00, reference: 54f7beb6-75b5-4489-ba62-99f750693a1f, type: showroom I want to group it by reference using django. I tried with: query = OpeningsHours.objects.filter(location_id=loc_id).query query.group_by = ['reference'] results = QuerySet(query=query, model=OpeningsHours) But it doesnt work. The query works fine but the result is not grouped by reference. Any idea? -
Django Add ManyToMany choices to existing ManyToMany
I am trying to add ManyToMany choices from a form to existing ManyToMany choices I have tried in views.py instance = form.save(commit=False) id.attendees.add(instance.attendees) instance.save() and in views.py instance = form.save(commit=False) for choice in instance.attendees: id.attendees.add(choice) form.save() The overall code is forms.py class LessonAddForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(LessonAddForm, self).__init__(*args, **kwargs) self.fields['attendees'].queryset = CustomUser.objects.filter( Q(username=user) | Q(customuser__username=user) ) class Meta: model = models.Lessons fields = ['attendees'] views.py def lessonRecord(request,id): if request.method == "POST": id = Lessons.objects.get(id=id) form = forms.LessonAddForm(request.POST,user=request.user,instance=id) if form.is_valid(): instance = form.save(commit=False) for choice in instance.attendees: id.attendees.add(choice) form.save() return redirect('lessons:lessonsView') else: id = Lessons.objects.get(id=id) #form = forms.LessonAddForm(instance=id) form = forms.LessonAddForm(instance=id , user=request.user) return render(request,'lessons/lesson_record.html',{'id':id,'form':form}) I just can't get my head round how to add my choices from the form to the existing choices -
Please help me create such grid view as in google news in django for python
I am making a website with Django Framework using python I just want this kind of gridview that is shown in the image. The images from Google News and I just wanted this kind of grid view with the image on the right hand side and all the text on the left please if you know grids in Django please provide me the code for the idea how to make this kind of gridview I know how to use grid in Django but I only know how to make square but I want this kind of gridview so please provide me the code if you can help me it would be really greatful for me enter image description here -
python django get html id at the backend
I'm trying to get html tag id at backend in views.py as well as redirecting to another html page. The html tag id is generated dynamically. Any idea will be helpful {% for getdata in names %} <li class="nav-item menu-items {% if 'ui-icons' in segment %} active {% endif %}" id="{{ getdata }}" name="ten"> <a class="nav-link" href="#" id="{{ getdata }}" class="complete_link"> <span class="menu-icon" id="{{ getdata }}" name="ten"> <i class="mdi mdi-contacts" id="{{ getdata }}" name="ten"></i> </span> <span class="menu-title" id="{{ getdata }}" name="ten"> {{getdata}} </span> </a> </li> {% endfor %} Thanks -
How do I format date from my django model in my react component?
I have a datetime field in my django model that looks like this: date_posted = models.DateTimeField('Date posted', auto_now_add=True) When I display it in my React component here <p>at : {comment.date_posted}</p> it looks like this : 2020-10-08T09:23:30.569790Z How can I change it too look something like this: 2020-10-08 09:23:30 ? -
type error Catching classes that do not inherit from Base Exception is not allowed
I am working on CS50 WEB 2020 Project 2, I want to save Data from form to models(Explained in code below). I have looked and studied exception but couldn't figure it out. Is there any alternate way to do this, or is there a thing I am missing here? P.S: I have marked where the error is rising Views.py def index(request): listingitems = Product.objects.all() context = {"listingitems":listingitems} return render(request, 'auctions/index.html', context) def productinfo(request, product_id): product = Product.objects.get(pk=product_id) return render (request, 'auctions/product.html', { "product":product }) def newproduct(request): if not request.user.is_authenticated: return HttpResponseRedirect(reverse("login")) else: if request.method == "POST": form = NewProductForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] description = form.cleaned_data["description"] img_url = form.cleaned_data["img_url"] price = form.cleaned_data["price"] category_name = dict(form.fields["cat"].choices)[int(form.cleaned_data["cat"])] try: #new product new_product = Product(title = title, #error here description = description, # cat = Category.objects.get(pk=category_name), img_url= img_url, author = request.user) new_product.save() #new bid new_bid = Bid(price = price, author = request.user, listing = new_product) new_bid.save() except IntegrityError(): return render(request, 'auctions/create.html',{ "message":"An Error Occured" }) return HttpResponseRedirect(reverse("productinfo", args=[new_product.id])) categories = Category.objects.all() context = {"form": NewProductForm()} return render(request, "auctions/create.html", context) forms.py obj = list(enumerate(Category.objects.all())) class NewProductForm(forms.Form): title = forms.CharField(label="Title", required=True) description = forms.CharField(label="Description", widget=forms.Textarea, required=False) price = forms.FloatField(label="Starting Price", required=True) img_url = forms.URLField(label="Image URL … -
Django App - Deployment on host (Beginners guide)
I have finished my first simple django app - online store. And now I am planning to deploy it on some free host. Goal is simple - just to have link which anyone can access in order to show the app somewhere else then on local computer. Can you recommend any beginner friendly video/guide with step-by-step explenation how to do it? -
How do I re-run npm build in React and Django?
So I'm learning React and Django, and executed npm run build to run the React App in my Django server (port 8000). Then I turned the React app off(ctrl+C), and now I'm trying to run it again. So I thought I should execute npm run build again, but it didn't work. I have the Django server running, but I have no idea how to start the React app. I know this may sound unclear, but this is the best I can explain as a beginner. How do I turn the React app back on? -
No live upstream while connecting to upstream jwilder/ngnix-proxy
The documentation is not clear to me, as well as this is my first deployment I keep getting error as 502 beacause of no live upstream. This is the code. docker.staging.yml version: '3.8' networks: public_network: name: public_network driver: bridge services: web: build: context: . dockerfile: Dockerfile.prod command: gunicorn djangotango.wsgi:application --bind 0.0.0.0:8000 volumes: # - .:/home/app/web/ - static_volume:/home/app/web/static - media_volume:/home/app/web/media expose: - 8000 env_file: - ./.env.staging db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.staging.db depends_on: - web pgadmin: image: dpage/pgadmin4 env_file: - ./.env.staging.db ports: - "8080:80" volumes: - pgadmin-data:/var/lib/pgadmin depends_on: - db links: - "db:pgsql-server" environment: - PGADMIN_DEFAULT_EMAIL=pgadmin4@pgadmin.org - PGADMIN_DEFAULT_PASSWORD=root - PGADMIN_LISTEN_PORT=80 nginx-proxy: build: ./nginx restart: always ports: - 443:443 - 80:80 volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro depends_on: - web networks: - public_network nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.staging.proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d depends_on: - nginx-proxy networks: - public_network volumes: postgres_data: pgadmin-data: static_volume: media_volume: certs: html: vhost: .env.staging.db VIRTUAL_HOST=djangotango.meghaggarwal.com VIRTUAL_PORT=8000 LETSENCRYPT_HOST=djangotango.meghaggarwal.com ngnix Docekrfile FROM jwilder/nginx-proxy COPY vhost.d/default /etc/nginx/vhost.d/default COPY custom.conf /etc/nginx/conf.d/custom.conf ngnix->vhost.d->default upstream djangotango { server web:8000; } server { listen 80; listen 443; server_name djangotango.meghaggarwal.com location / { proxy_pass http://djangotango; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; … -
How do I get data from a form while the user is typing in his data? Django/Python
I have a problem I am currently working on. Really new to django and python. What I am trying to do is I have a form where the user can rent a parking lots for a certain period of time. I want to be able to dynamically calculate the value of the price based on the time the user selects and show this to the user. Meaning that price x time selected will generate a price that the user should be able to see. I do have the view ready and started with a function to calculate the price, but I got stuck really fast since I can't come up with how to get the user input data before the form, where the data is entered, is submited. Below you see the view i wrote to this: def list_parking_lots(request): """ View for all parking lots :param request: request from user :return: rendered parking_mgmt/list_parking_lots.html """ parking_lots = ParkingLot.objects.all() form = ReservationForm() if request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your reservation was successfully registered.') form = ReservationForm() return render(request, 'parking_mgmt/list_parking_lots.html', {'parking_lots': parking_lots, 'form': form}) Any help is appreciated. -
Check if a parameter exists in Django URL
I am trying to get a URL if it exists in the URL but keep getting the following error: django.utils.datastructures.MultiValueDictKeyError: 'sc' The case is that the urls can be sometimes like the following: /allot-graph/ and sometimes: /allot-graph/?sc='foo' and in my function I am doing this: class AllotmentbyMonth(APIView): def get(self, request): q = request.GET['sc'] if q: print("q", q) dataset = some query else: dataset = some query -
Django Multiple requests in One Time
Now I Am Work On 'Django Multiple Requests In One Time', But When I Send the First Request And At The Time I Send the Second Request So I Get The Result of The Second Request, First Request is Closed automatically, So How I Implement Multiple Requests In One Time, Please Suggest To Me. Note:- I Work In LocalHost -
Check if list of objects contain an object with a certain attribute value in django template tags
I want to check if my list of objects contain an object with a certain attribute value in django tempate tags.as we know it is represented in python like: any(x.name == "t2" for x in l) so, is there some tags to express this in template tags something like: {% if any x.atype == "Other" for x in list %} {% endif %} or something else do that?