I’m starting to work with Django, and I’m starting a test to solidify what I’ve been learning. The idea is a single page, which displays a sentence as soon as the site opens. Below the phrase, there is a button that I would like to change the phrase to some other phrase coming from a variable declared in models.py and which contains several phrases that were registered through Django’s admin panel.
This is my models.py file:
from django.db import models
class Base(models.Model):
criado = models.DateField('Criado', auto_now_add=True)
modificado = models.DateField('Atualização', auto_now=True)
ativo = models.BooleanField('Ativo', default=True)
class Meta:
abstract = True
class Frase(Base):
frase = models.CharField('Frase', max_length=100)
dica = models.CharField('Dica', max_length=200, default='-')
class Meta:
verbose_name = 'Frase'
verbose_name_plural = 'Frases'
def __str__(self):
return self.frase
This is my views.py file:
from django.views.generic import TemplateView
from .models import Frase
class IndexView(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['frases'] = Frase.objects.order_by('?').all()
return context
This is my index.html:
<div class="container px-4 px-lg-5 h-100">
<div class="row gx-4 gx-lg-5 h-100 align-items-center justify-content-center text-center">
<div class="col-lg-8 align-self-end">
<h1 class="text-white font-weight-bold" id="frase">{{ frases|first }}</h1>
<hr class="divider" />
</div>
<div class="col-lg-8 align-self-baseline">
<a class="btn btn-primary btn-xl" onclick="nova_frase()">Nova frase</a>
</div>
</div>
</div>
(...) <!--rest of the html code-->
<script>
$('#gera_frase')
.on('click', () => document.getElementById('texto').innerText = '{{ frases|random }}')
</script>
The first click works, for ‘{{ frases|random }}’ is replaced by a random phrase from the QuerySet Phrases. I would like that, at each button click, a new phrase would appear on the screen, without having to reload the page.
Please help me so I can continue my studies. I’ve been stuck on this for almost two weeks now.