Reputation: 73
I'm have a page Detail View with a button with link for Detail View. But like the url need a PK, i cannot set PK per be a Detail View. How can I define a url for the previous page without the PK ?
In Template
<button id="botaoVoltar" type="submit" class="mb-10 btn btn-light"><a href="{% url 'relatorio' ??? %}">Voltar</a> </button>
In urls
path('relatorios/relatorio/<int:pk>', RelatorioView.as_view(), name='relatorio')
Exception:
NoReverseMatch Exception Value:
Reverse for 'relatorio' with no arguments not found. 1 pattern(s) tried: ['relatorios/relatorio/(?P[0-9]+)$']
Upvotes: 1
Views: 87
Reputation: 476729
You can define a method to look up the previous object:
class RelatorioView(DetailView):
# …
def get_previous(self):
return self.get_queryset().filter(
pk__lt=self.object.pk
).order_by('-pk').first()
Next we can use that to obtain the previous one:
{% with prev=view.get_previous %}
{% if prev %}
<button id="botaoVoltar" type="submit" class="mb-10 btn btn-light">
<a href="{% url 'relatorio' prev.pk %}">Voltar</a>
</button>
{% endif %}
Upvotes: 1