My models.py:
class Recipe(models.Model):
recipe_title = models.CharField("Назва Рецепту", max_length=50)
recipe_text = models.TextField("Текст Рецепту")
recipe_image = models.ImageField(default="", null=True, blank=True, upload_to="recipeImages/")
isHot = models.BooleanField(default=False)
isVegan = models.BooleanField(default=False)
author_name = models.CharField("Імʼя автора", max_length=100)
pub_date = models.DateTimeField("Дата публікації")
def __str__(self):
return self.recipe_title
def isHOT(self):
if self.isHot == True:
return self.recipe_title
My views.py:
def index(request):
latest_recipes = Recipe.objects.order_by('-pub_date')[:5]
search_query = request.GET.get('search', '')
if 'ishot' in request.POST:
recipes = Recipe.objects.filter(isHot=True).all()
else:
recipes = Recipe.objects.all()
if search_query:
recipes = Recipe.objects.filter(recipe_title__icontains=search_query)
else:
recipes = Recipe.objects.all()
return render(request, 'recipes/list.html', {'latest_recipes': latest_recipes, 'recipes': recipes})
My html page:
{% for a in recipes %}
<a href="{% url 'recipes:detail' a.id %}" style="text-decoration: none; color: black;">
<div class="row">
<div class="column">
<div class="card">
<img src="{{a.recipe_image.url}}" style="width: 15%; float:left">
<div id="text">
<h3>{{a.recipe_title}}</h3>
<p>{{a.recipe_text}}</p>
{% if a.was_published_recently %}
<h4 style="color: red;">NEW</h4>
{% endif %}
{% if a.isHOT %}
<img style="width:3%;" src="/images/hot.png" name="#">
{% endif %}
{% if a.isVEGAN %}
<img style="width:3%;" src="/images/vegan.png" name="#">
{% endif %}
</div>
</div>
</div>
</a>
{% endfor %}
'search_query' function works, 'ishot' function itself works as well, but filter 'recipes = Recipe.objects.filter(isHot=True).all()' doesn't. It should filter objects, similar function do it's job, I have no clue what is problem in
You are making GET request to the view, but you are looking for ishot
in request.POST
. Hence you should fix it by:
if request.GET.get('ishot', False):
recipes = Recipe.objects.filter(isHot=True).all()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.