Hello iam making game administration website with django and i need help with sorting 2 queryes . These are my models.
class Game(models.Model):
game_name = models.CharField(max_length=30, primary_key=True)
stages = models.IntegerField(null=False)
registration_start = models.DateTimeField(null=False, blank=False)
registration_end = models.DateTimeField(null=False, blank=False)
game_start = models.DateTimeField(null=False, blank=False)
game_end = models.DateTimeField(null=False, blank=False)
max_players = models.IntegerField(null=False)
class GameControl(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
game_name = models.ForeignKey(Game,
on_delete=models.CASCADE)
start_time = models.DateTimeField(null=True, blank=True)
end_time = models.DateTimeField(null=True, blank=True)
progress = models.IntegerField(null=True, default=0)
game_time = models.DurationField(null=True, blank=True)
models
and i need to separate from them registered game_names and unregistered game_names
#login_required(login_url='/signin')
def home(request):
current_user = request.user
registered = GameControl.objects.filter(user=current_user)
unregistered = Game.objects.all()
return render(request, "games/home.html", {'unregistered': unregistered ,'registered': registered })
view
I was trying to make this in template but it didnt work
{% for un in unregistered %}
{% if un.game_name in registered.game_name %}
<button type="button" class="btn">{{un.game_name}}
<i class="material-icons" style="float:
right;">close</i></span></button>
<br>
{% else %}
<button type="button" class="btn">{{un.game_name}}
<i class="material-icons" style="float:
right;">arrow_forward</i></span></button>
<br>
{% endif %}
{% endfor %}
template
Help Please <3.
Basically, in the view you should just create a list of registered game names:
#login_required(login_url='/signin')
def home(request):
current_user = request.user
registered = GameControl.objects.filter(user=current_user)
unregistered = Game.objects.all()
return render(request, "games/home.html", {'unregistered': unregistered ,'registered_names': [reg.game_name for reg in registered] })
And then the template:
{% for un in unregistered %}
{% if un.game_name in registered_names %}
<button type="button" class="btn">{{un.game_name}}
<i class="material-icons" style="float:
right;">close</i></span></button>
<br>
{% else %}
<button type="button" class="btn">{{un.game_name}}
<i class="material-icons" style="float:
right;">arrow_forward</i></span></button>
<br>
{% endif %}
{% endfor %}
Related
Django version = 4.0.4
Python == 3.9.12
os = osx
here is my cart template, where I use a template tag to get access to my Order instance data for render it
<div class="block-cart action">
<a class="icon-link" href="{% url 'core:cart' %}">
<i class="flaticon-shopping-bag"></i>
<span class="count">{{ request.user|cart_item_count }}</span>
<span class="text">
<span class="sub">Carrito:</span>
Gs.{{ request.user|cart_total_count }} </span>
</a>
<div class="cart">
<div class="cart__mini">
<ul>
<li>
<div class="cart__title">
<h4>Carrito</h4>
<span>( {{ request.user|cart_item_count }} Item en el carrito)</span>
</div>
</li>
{% if request.user|cart_total_items != 0 %}
{% for order_item in request.user|cart_total_items %}
<li>
<div class="cart__item d-flex justify-content-between align-items-center">
<div class="cart__inner d-flex">
<div class="cart__thumb">
<a href="product-details.html">
<img src="{{ order_item.item.image.url }}" alt="">
</a>
</div>
<div class="cart__details">
<h6>{{ order_item.item.title }}</h6>
<div class="cart__price">
<span>Gs. {% if order_item.item.discount_price|stringformat:".0f" %} {{ order_item.item.discount_price|stringformat:".0f" }}
{% else %} {{ order_item.item.price|stringformat:".0f" }}
{% endif %} x {{order_item.quantity}}</span>
</div>
</div>
</div>
<div class="cart__del">
<i class="fal fa-times"></i>
</div>
</div>
</li>
{% endfor %}
{%else%}
{% endif %}
<li>
<div class="cart__sub d-flex justify-content-between align-items-center">
<h6>Subtotal</h6>
<span class="cart__sub-total">Gs.{{ request.user|cart_total_count }}</span>
</div>
</li>
<li>
Ver Carrito
Finalizar Compra
</li>
</ul
</div>
</div>
here is the custom template tag
#register.filter
def cart_item_count(user):
if user.is_authenticated:
qs = Order.objects.filter(user=user, order_completed=False)
qs = qs.last()
if qs.order_completed == False:
print(qs.order_completed)
return qs.items.count()
else:
return 0
return 0
here my model
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
company_name = models.CharField(max_length=100, null=True, blank=True)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
direction = models.CharField(max_length=100, blank=True, null=True)
city = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=200, null=True, blank=True)
received = models.BooleanField(default=False)
order_completed = models.BooleanField(default=False)
class Meta:
verbose_name = "Pedido"
verbose_name_plural = "Pedidos"
ordering = ['-id']
def __str__(self):
return self.user.username
def get_total(self):
total = 0
for order_item in self.items.all():
total += order_item.get_total_item_price()
return total
here my checkout view
class CheckoutView(View):
def get(self, *args, **kwargs):
try:
order = Order.objects.get(user=self.request.user, order_completed=False)
form = CheckoutForm()
context = {
'form': form,
'order': order,
}
order.save()
return render(self.request, "v2/checkout.html", context)
except ObjectDoesNotExist:
messages.info(self.request, "Usted no tiene un pedido activo")
return redirect("core:checkout")
def post(self, *args, **kwargs):
form = CheckoutForm(self.request.POST or None)
try:
order = Order.objects.get(user=self.request.user, order_completed=False)
if form.is_valid():
order = form.save(commit=False)
order.order_completed = True
order.user = self.request.user
order.save()
return HttpResponseRedirect('success')
except ObjectDoesNotExist:
messages.warning(self.request, "Usted no posee ningún pedido aun")
return redirect("core:cart")
return HttpResponseRedirect('v2/checkout')
what im tryng is when y make the post form from checkout i save my order change it property order_completed to True, redirect to a succes page, but even if a reload the page, the value of my cart still with the last Order, even if try to filter it by it property
here is my admin interface from my order model before i send the POST
Here is after the POST
here when i go to my redirect succes page it suppose that i have to see my cart empty because the filter template tag but, my order still with the old information
even if i reload cleaning cache still wrong, what im doing wrong?, whats is the correct way to do this?
I am working on a To-do app. The individual to-dos reference a to-do list via a foreign key and the to-do lists reference a project via a foreign key.
I want the to-do's status to be set to true when clicked. I have seen some tutorials where this is done but I haven't been able to get this to work yet.
Here are the models:
class Project(models.Model):
title = models.CharField(max_length= 200)
description = tinymce_models.HTMLField()
status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active")
date = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse ('project_detail', args=[str(self.id)])
class ProjectTodoGroup(models.Model):
title = models.CharField(max_length=250)
description = tinymce_models.HTMLField()
project = models.ForeignKey(Project, blank=True, on_delete=models.CASCADE, related_name='todo_group')
date = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.title
class ProjectTodo(models.Model):
title = models.CharField(max_length= 250)
notes = tinymce_models.HTMLField()
status = models.BooleanField(default=False)
projectgroup = models.ForeignKey(ProjectTodoGroup, blank=True, null=True, on_delete=models.CASCADE, related_name='todo_set')
date = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.title
The view:
model = ProjectTodo
fields = ['status']
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk'))
return context
def get_success_url(self):
return reverse('company_project:todo_group_detail', args=[self.kwargs.get('pk'), (self.object.id)])
Everything I have tried to far with the view hasn't worked.
The template:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="section-container container">
<div class="todo-group">
<h2>{{ projecttodogroup.title }}</h2>
<p>{{ projecttodogroup.description | safe }}</p>
</div>
<div><b>Todos</b></div>
{% if projecttodogroup.todo_set.all %}
{% for todo in projecttodogroup.todo_set.all %}
<div class="todos" style="padding: 10px;">
{{ todo.title }}
</div>
{% endfor %}
{% else %}
<p>No Todos have been have been added yet.</p>
{% endif %}
<h1>Add Todo</h1>
<form action="" method="post">
{% csrf_token %}
{{ form.media }}
{{ form|crispy }}
<input type="submit" value="save">
</form>
</div>
{% endblock content %}
I am having some trouble getting a file to post via a form using generic class-based view CreateView. Below is what i have so far. I am not quite sure how to handle the file and if request.FILES is getting the file being posted or if there is something else i need to be doing to capture the file information in the form. I have tried following the docs, however no luck in getting something working. File uploads as a blank field.
views.py
# Create
class FileUploadCreateView(BSModalCreateView):
template_name = 'fileupload/create-file.html'
form_class = FileUploadModelForm
success_message = 'Success: File was uploaded.'
success_url = reverse_lazy('files_list')
# Add required field my_user prior to posting form
def form_valid(self, form):
form = FileUploadModelForm(self.request.POST, self.request.FILES)
self.object = form.save(commit=False)
self.object.my_user = self.request.user
self.object.file_status = 'ready'
return super().form_valid(form)
forms.py
class FileUploadModelForm(BSModalModelForm):
class Meta:
model = FileUpload
fields = ['file_name', 'file_description', 'file_date_from', 'file_date_to','file_upload']
widgets = {
'file_name': forms.TextInput(attrs={'class':'form-control mb-3', 'id':'ruleset_name'}),
'file_description': forms.Textarea(attrs={'rows':5}),
'file_date_from': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": True,
"showClear": True,
"showTodayButton": True,
}
),
'file_date_to': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": True,
"showClear": True,
"showTodayButton": True,
}
),
'file_upload': forms.FileInput(attrs={'class':'form-control-file mb-3', 'id':'file_upload', 'type':'file', }),
}
html
{% load widget_tweaks %}
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title" style="color:#7a7a7a;">
<i class="fas fa-plus-square fa-med pr-2 align-middle"></i>
<span class="align-middle">ADD File</span>
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% for field in form %}
<div class="form-group">
<label for="{{ field.id_for_label }}" style="font-size: small; color:#7a7a7a;">{{ field.label }}</label>
{% render_field field class="form-control" %}
<div class="{% if field.errors %} invalid{% endif %}">
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="submit-btn btn btn-primary pr-4 pl-4">Save</button>
</div>
</form>
model.py
class FileUpload(models.Model):
"""
Class for the creation of file uploads
"""
id = models.AutoField(primary_key=True)
my_user = models.ForeignKey('users.MyUser', on_delete=models.CASCADE, related_name='file_uploads', default=None)
file_name = models.CharField(max_length=255, blank=False, default=None, verbose_name='File Name')
file_description = models.CharField(max_length=255, blank=False, default=None, verbose_name='File Description')
file_date_from = models.DateField(default=None, null=True, blank=False, verbose_name='File Date From')
file_date_to = models.DateField(default=None, null=True, blank=False, verbose_name='File Date To')
STATUS_CHOICES = (
('ready','Ready'),
('processed', 'Processed'),
('archived','Archived'),
)
file_status = models.CharField(max_length=9, choices=STATUS_CHOICES, default=None, blank=False, verbose_name='File Status')
file_create_date = models.DateTimeField(verbose_name='File Create Date', auto_now_add=True)
file_upload = models.FileField(upload_to='uploads/%Y/%m/%d/', default=None, verbose_name='File Upload', blank=True)
class Meta:
ordering = ['-file_create_date']
constraints = [
models.UniqueConstraint(fields=['my_user','file_name'], name='Unique MyUser File')
]
def __str__(self):
return self.file_name
Pretty sure you forgot to add the enctype="multipart/form-data" data attribute to the form tag in your template.
To be sure, you would have to provide us with the Model, the Form and the template code.
after working on the view for some time, I was able to get the file to post via the following, using cleaned_data.
# Add required fields prior to posting form
def form_valid(self, form):
self.instance = form.save(commit=False)
self.instance.my_user = self.request.user
self.instance.file_status = 'ready'
self.instance.file_upload = form.cleaned_data['file_upload']
return super().form_valid(form)
I'm trying to set up magnific popup on django.
My goal is to have one main picture in the homepage overview gallery view, which when clicked, would open a popup with the related images from the same photoshoot i.e. images with the same ID or PK.
I tried to apply the following approach
but i just cannot get it to work, maybe someone could help me out in this
My models.py
class Item(models.Model):
name = models.CharField(blank=False, max_length=200)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL)
order = models.IntegerField(blank=True, null=True)
active = models.BooleanField(blank=True, default=False)
objects = models.Manager()
class Meta:
verbose_name_plural = 'items'
def __str__(self):
return self.name
class ItemImage(models.Model):
image = ProcessedImageField(
blank=True,
null=True,
processors=[ResizeToFit(width=1680, upscale=False)],
format='JPEG',
options={'quality':90})
order = models.IntegerField(blank=True, null=True)
main = models.BooleanField(blank=True, default=False)
cover = models.BooleanField(blank=True, default=False)
item = models.ForeignKey(Item, related_name='items', blank=True, null=True, on_delete=models.SET_NULL)
objects = models.Manager()
class Meta:
verbose_name_plural = 'item images'
Views.py
def portraits(request):
port = ItemImage.objects.filter(item__category__slug='portraits', item__active=True, main=True,).order_by('item__order')
portall = ItemImage.objects.filter(item__category__slug='portraits', item__active=True).order_by('item__order')
context = {
'main_portraits': port,
'all_portraits': portall
}
return render(request, 'gallery/portraits.html', context)
and Template:
{% block content %}
<div class="grid">
{% for pic in main_portraits %}
<div class="item">
<div class="item">
<div class="outer-text">
<div class="text">
{{ pic.item.name }}
<p>Click to view gallery</p>
</div>
</div>
<a><img class="lazy" alt=""
sizes="(min-width:1400px) 1220px
(min-width:1000px) 1000px,
(min-width:500px) 700px,
(min-width:320px) 420px,
280px"
srcset="{{ pic.image_xs.url }} 280w,
{{ pic.image_s.url }} 420w,
{{ pic.image_m.url }} 700w,
{{ pic.image_l.url }} 1000w,
{{ pic.image_xl.url }} 1220w" />
</a> {{ pic.item.pk }}
</div>
<div class="lazy">
{% for p in all_portraits %}
{% endfor %}
</div>
</div>
{% endfor %}
</div>
{% endblock %}
I have set
z.item.pk
just as a test, to see if any of my manipulations result in the pk's to bunch up. For example the first for-loop returns a picture with PK "24", I need for the second for-lop to return only images with the same PK; and so for every image. I think the answer might be connected with _set.all function, just like in the related question above, but I cant seem to get it to work in my case. Feels like I'm missing something here.
current output:
<div class="grid">
<div class="item">
<div class="item">
<div class="outer-text">
<div class="text">
Palagā tītā
<p>Click to view gallery</p>
</div>
</div>
<a><img class="lazy" alt=""
sizes="(min-width:1400px) 1220px
(min-width:1000px) 1000px,
(min-width:500px) 700px,
(min-width:320px) 420px,
280px"
srcset="/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/958ba5dbee5efe28fd2f5054b8f819e1.jpg 280w,
/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/02d12ca7f0633fee2fc762cf96f7889e.jpg 420w,
/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/ba5fa6633e92a288e3b2f47a713d64c2.jpg 700w,
/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/fe0d559fef5b02434c43f841005d4961.jpg 1000w,
/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/96d0e52dff14d1bc4b60bbec674565db.jpg 1220w" />
</a> 24
</div>
<div class="lazy">
</div>
</div>
You need prefiltered querysets containing the related images for every main image before handing over to the template.
def portraits(request):
ports = ItemImage.objects.filter(item__category__slug='portraits', item__active=True, main=True,).order_by('item__order')
for p in ports:
# You may not need the item__category__slug filter
# if there are only images of the same category
# associated with an item.
# Also, if you want to exclude the main image
# from the set of related images, you need to add the filter
# main=False
p.related_images = ItemImage.objects.filter(item__category__slug='portraits', item__id=p.item.id)
context = {
'main_portraits': ports,
}
return render(request, 'gallery/portraits.html', context)
Then you can loop over main_portraits in the template, and get the related images for each main image in a nested loop:
{% for mainp in main_portraits %}
{% for im in mainp.related_images %}
{# do something with the related images #}
{% endfor %}
{% endfor %}
You can break down the models like this it will make the querying easier.
# models.py
class Item(mdoels.Model):
name = models.CharField(blank=False, max_length=200)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL)
...
display_image = models.ProcessedImageField(...)
class ItemImage(models.Model):
item = models.ForeignKey(Item, related_name='images', blank=True, null=True, on_delete=models.SET_NULL)
image = models.ProcessedImageField(...)
...
#views.py
def portraits(request):
items = Item.objects.filter(category__slug='portraits', active=True)
return render(request, 'gallery/portraits.html', context={items: items})
#template
{% for item in items %}
<h1> {{item.name}} </h1>
<img src={{item.display_image}} />
{% for item_image in item.images.all %}
<img src={{item_image.image}} />
{% endfor %}
{% endfor %}
Coming from Angular, this was easy to do, but I am not sure where to begin on creating a dropdown form that will filter from a list of objects. Basically, I have the code below, that will pull in and display all real estate listings; I would like to create a dropdown that will have 2 selections, 'Featured' and 'New Listing' and when a user selects one, the list will filter out and display only those listings that match. Thank you for your help.
Here is my model
from django.db import models
from django.utils import timezone
class Listing(models.Model):
FAIR = 'FAIR'
GOOD = 'GOOD'
VERY_GOOD = 'VERY_GOOD'
EXCELLENT = 'EXCELLENT'
NEW_LISTING = 'NEW_LISTING'
PRICE_REDUCED = 'PRICE_REDUCED'
UNDER_AGREEMENT = 'UNDER_AGREEMENT'
SOLD = 'SOLD'
YES = 'YES'
NO = 'NO'
FULL_SERVICE = 'FULL_SERVICE'
FOR_LEASE = 'FOR_LEASE'
WITH_REAL = 'WITH_REAL'
QUICK_SERVE = 'QUICK_SERVE'
CONDITION_CHOICES = (
('FAIR', 'Fair'),
('GOOD', 'Good'),
('VERY_GOOD', 'Very Good'),
('EXCELLENT', 'Excellent'),
)
STATUS_CHOICES = (
('NEW_LISTING', 'New Listing'),
('PRICE_REDUCED', 'Price Reduced'),
('UNDER_AGREEMENT', 'Under Agreement'),
('SOLD', 'Sold'),
)
FEATURED_CHOICES = (
('YES', 'Yes'),
('NO', 'No'),
)
LOCATION_TYPE = (
('FULL_SERVICE', 'Full Service'),
('FOR_LEASE', 'For Lease'),
('WITH_REAL', 'With Real'),
('QUICK_SERVE', 'Quick Serve'),
)
photo = models.ImageField(upload_to="media/properties/", max_length=250, blank=True, null=True)
broker = models.ForeignKey('auth.User')
phone = models.CharField(max_length=20, null=True)
title = models.CharField(max_length=250, null=True)
description = models.TextField(null=True)
concept = models.CharField(max_length=250, null=True)
location = models.CharField(max_length=250, null=True)
size = models.CharField(max_length=250, null=True)
seating = models.CharField(max_length=250, null=True)
condition_choices = models.CharField(max_length=20, choices=CONDITION_CHOICES, blank=True)
hours = models.CharField(max_length=250, null=True)
asking_price = models.CharField(max_length=250, null=True)
sales_price = models.CharField(max_length=250, null=True)
rent_price = models.CharField(max_length=250, null=True)
lease_terms = models.CharField(max_length=250, null=True)
licenses = models.CharField(max_length=250, null=True)
parking = models.CharField(max_length=250, null=True)
status_choices = models.CharField(max_length=20, choices=STATUS_CHOICES, blank=True, null=True)
featured_choices = models.CharField(max_length=5, choices=FEATURED_CHOICES, blank=True, null=True)
location_type = models.CharField(max_length=20, choices=LOCATION_TYPE, blank=True, null=True)
created_date = models.DateTimeField(default=timezone.now, null=True)
published_date = models.DateTimeField(default=timezone.now, null=True)
listing_order = models.PositiveIntegerField(default=0, blank=False, null=False)
class Meta(object):
ordering = ('listing_order',)
def publish(self):
"""This is a docstring"""
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
And here is my template
{% extends "listing/base.html" %}{% load staticfiles %}
{% block content %}
<section class="listings mt64 mb64">
<div class="container">
{% for listing in listings %}
<div class="row">
<div class="col-md-4">
<div class="listings-photo" style="background: #ccc url('{{ MEDIA_URL }}{{ listing.photo.name }}')no-repeat 50% 50%; background-size: cover; width: 350px; height: 220px"></div>
</div>
<div class="col-md-8">
<h3 class="uppercase">{{ listing.title }}</h3>
<p><span class="listings-title">Description:</span> {{ listing.description }}</p>
<div class="row">
<div class="col-md-6">
<ul>
<li><span class="listings-title">Concept:</span> {{ listing.concept }}</li>
<li><span class="listings-title">Location:</span> {{ listing.location }}</li>
<li><span class="listings-title">Size:</span> {{ listing.size }}</li>
<li><span class="listings-title">Seating:</span> {{ listing.seating }}</li>
<li><span class="listings-title">Condition:</span> {{ listing.condition_choices }}
</li>
<li><span class="listings-title">Hours:</span> {{ listing.hours }}</li>
</ul>
</div>
<div class="col-md-6">
<ul>
<li><span class="listings-title">Asking Price:</span> {{ listing.asking_price }}
</li>
<li><span class="listings-title">Sales:</span> {{ listing.sales_price }}</li>
<li><span class="listings-title">Rent:</span> {{ listing.rent_price }}</li>
<li><span class="listings-title">Lease Terms:</span> {{ listing.lease_terms }}</li>
<li><span class="listings-title">Licenses:</span> {{ listing.licenses }}</li>
<li><span class="listings-title">Parking:</span> {{ listing.parking }}</li>
</ul>
</div>
</div>
<p>For more information please contact {{ user.first_name }} {{ user.last_name }} at {{ listing.phone }}.</p>
</div>
</div>
{% endfor %}
</div>
</section>
{% endblock content %}
I can see what you mean coming from Angular. The most classical way of doing that in Django would be creating a form with all the fields you need, then passing it to the view to process the data, filter records and pass them back to the template. I'll try to provide a basic example so you can hopefully get the idea:
Index.html:
<form action="{% url 'index' %}" method="get">
<label for="featured">Format</label>
<select name="featured">
<option value="Yes" />Yes</option>
<option value="No" />No</option>
<input type="submit" name="featured" value="Filter" />
</form>
Views.py
def index(request, template_name='index.html'):
if request.GET.get('featured'):
featured_filter = request.GET.get('featured')
listings = Listing.objects.filter(featured_choices=featured_filter)
else:
listings = Listing.objects.all()
context_dict = {'listings': listings}
return render(request, template_name, context_dict)
This is pretty self-explanatory. If there's a "featured" parameter in GET, list will get filtered, otherwise it will pass all objects. Obviously we're looking at page refresh every filter request, if you expect a bit more of a one-page experience, you have to go for ajax and post requests, or something. Also, keep in mind this snippet is just a hard-coded example. Ideally, you would want to create a ModelForm class and instantiate that, then pass it to the template - a lot more readable and maintainable if you have more filter fields. If there's complex filtering involved, you would also probably want to have an additional view for filtering purposes, but this works too, it just gets messy really quick.
Thanks for Zephi, your tip helped me a lot, but for me, only worked after I changed index.html to this:
index.html
<form action="{% url 'index' %}" method="get">
<label for="featured">Format</label>
<select name="featured">
<option value="Yes" />Yes</option>
<option value="No" />No</option>
</select> <!-- ADDED THIS LINE -->
<input type="submit" value="Filter" /> <!-- DELETE name="featured" FROM ORIGINAL CODE -->
</form>
here fragments from my app's code:
index.html
<form action="{% url 'index' %}" method="get">
<label for="featured">Format</label>
<select name="featured">
{% for adoption in typeList %}
<option value="{{ adoption }}">{{ adoption }}</option>
{% endfor %}
</select>
<input type="submit" value="Filter" />
</form>
views.py
def index(request, template_name='index.html'):
if request.GET.get('featured'):
featured_filter = request.GET.get('featured')
query = Unit.listType.filter(unitType=featured_filter)
else:
query = Unit.listType.all()
typeList = query.order_by('unitType').values_list('unitType',flat=True).distinct()
_dict = {}
for x in range(len(typeList)):
_dict[typeList[x]] = typeList[x]
return render(request, 'index.html', {'query':query, 'typeList':_dict})