show last viewd recipes on search page

This commit is contained in:
vabene1111 2020-05-11 12:42:55 +02:00
parent 123dc1a74d
commit 4a68a99907
4 changed files with 52 additions and 1 deletions

View File

@ -0,0 +1,25 @@
# Generated by Django 3.0.5 on 2020-05-11 10:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('cookbook', '0043_auto_20200507_2302'),
]
operations = [
migrations.CreateModel(
name='ViewLog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cookbook.Recipe')),
],
),
]

View File

@ -248,3 +248,12 @@ class CookLog(models.Model):
def __str__(self):
return self.recipe.name
class ViewLog(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.recipe.name

View File

@ -77,6 +77,13 @@
{% endif %}
<br/>
{% if last_viewed %}
<h4>{% trans 'Last viewed' %}</h4>
{% render_table last_viewed %}
<h4>{% trans 'Recips' %}</h4>
{% endif %}
{% if user.is_authenticated and recipes %}
{% render_table recipes %}
{% else %}

View File

@ -8,6 +8,7 @@ from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse_lazy
from django.utils import timezone
from django_tables2 import RequestConfig
from django.utils.translation import gettext as _
@ -42,7 +43,12 @@ def search(request):
table = RecipeTableSmall(f.qs)
RequestConfig(request, paginate={'per_page': 25}).configure(table)
return render(request, 'index.html', {'recipes': table, 'filter': f})
if request.GET == {}:
last_viewed = RecipeTable(Recipe.objects.filter(viewlog__created_by=request.user).order_by('-viewlog__created_at').all()[0:5])
else:
last_viewed = None
return render(request, 'index.html', {'recipes': table, 'filter': f, 'last_viewed': last_viewed})
else:
return render(request, 'index.html')
@ -78,6 +84,10 @@ def recipe_view(request, pk):
comment_form = CommentForm()
bookmark_form = RecipeBookEntryForm()
if request.user.is_authenticated:
if not ViewLog.objects.filter(recipe=recipe).filter(created_by=request.user).filter(created_at__gt=(timezone.now()-timezone.timedelta(minutes=5))).exists():
ViewLog.objects.create(recipe=recipe, created_by=request.user)
return render(request, 'recipe_view.html',
{'recipe': recipe, 'ingredients': ingredients, 'comments': comments, 'comment_form': comment_form,
'bookmark_form': bookmark_form})