Семантически «правильный» способ выполнить эту работу - значительно переписать код:
Сначала вам нужно изменить urls.py в вашей базовой папке, чтобы URL-адрес флэш-карты принимал идентификатор флэш-карты,Это позволит вам посетить флэш-карту / 1 /, флэш-карту / 2 / и т. Д. И просмотреть данные для соответствующей флэш-карты.
urls.py
from django.contrib import admin
from django.urls import path, include
from flash import views
urlpatterns = [
path('admin/', admin.site.urls),
path('flashcard/<int:card>/',views.index,name='flashcard'), # Here we are adding a variable to the URL pattern, which will be passed to the view
]
Затем вам нужно изменить свое представление так, чтобы оно брало идентификатор карточки из URL и отображало карточку, о которой идет речь:
views.py
def flashcard(request, card=1): # Your view will now look for the 'card' variable in your URL pattern.
flash_dict = {'flashcards': Card.objects.get(pk=card)} # Your 'flashcards' variable now holds the card that corresponds to the ID in the URL
return render(request, 'flash/index.html', context=flash_dict)
Затеммы напишем метод в вашей модели Card, который будет вызывать следующую карту при вызове self.get_next.Теперь, если у вас есть объект Card, вы можете найти следующую карту, вызвав card.get_next ():
models.py
from django.db import models
# Create your models here.
class Card(models.Model):
flash_question = models.TextField()
flash_answer = models.TextField()
objects = models.Manager()
def __str__(self):
return self.flash_question
def get_next(self):
next = Card.objects.filter(id__gt=self.id).order_by('id').first()
if next:
return next
# If the current card is the last one, return the first card in the deck
else:
return Card.objects.all().order_by('id').first()
Наконец, мыЗаменим кнопки в вашем шаблоне ссылкой, которая ссылается на новое представление «карточки», и передаст ей идентификатор следующей карточки в следующей последовательности:
template.html
<div class = "jumbotron">
{% if flashcards %}
<p class = 'question'>{{ flashcards }}</p>
<p class = 'answer'>{{ flashcards.flash_answer }}</p>
<!-- Here we link to the 'flashcard' view, and pass it the ID of the next card in the sequence -->
<a href="{% url 'flashcard' flashcards.get_next.id %}">Next flashcard</a>
{% else %}
<p>NO ACCESS RECORDS FOUND!</p>
{% endif %}
</div>
Теперь попробуйте посетить / flashcard / 1, чтобы увидеть, как все работает вместе.