How to make Django redirect to other page?
I have an app named "works" where all my works should contain. There are cards-previews to my works. So I want them clickable and redirecting to the work that is clicked and soon shown the html file of the work. The problem is in redirecting to that work.
In myapp/urls.py is the following
urlpatterns = [
path("", WorksView.as_view(), name="works"),
path("<slug:work_slug>/", WorkDetailView.as_view(), name="work-detail"),
]
myapp/models.py
class Works(models.Model):
-- other attributes --
slug = models.SlugField(
null=False,
db_index=True,
blank=False,
max_length=255,
unique=True,
verbose_name="URL",
)
def get_absolute_url(self):
from django.urls import reverse
return reverse("work-detail", kwargs={"work_slug": self.slug})
So what class based view should be used in myapp/views.py for WorkDetailView? I have tried View, TemplateView, RedirectView, but neither of them work properly that I want to.
The last try was that:
class WorkDetailView(View):
def get(self, request, *args, **kwargs):
work = get_object_or_404(
Works, slug=kwargs["work_slug"]
)
print(work.get_absolute_url())
return render(request, work.get_absolute_url(), {"works_data": work})
The work.get_absolute_url works good, but Django cant find template
My project folder:
But when I change the return string to return render(request, f"{work.get_absolute_url()[1:-1]}.html", {"work": work})
it works and prints "works/not-found/", but I dont think that it is the correct way
So how can I do it right?
The last try was to make that using View but Django tells TemplateDoesNotExist at /works/not-found/
This is fragment from my work.html
{% block body %}
<div class="intro" id="#intro">
<div class="container">
<div class="works">
{% for work in works_data %}
<a href="{{ work.get_absolute_url }}" class="work__item">
{% if work.preview %}
<img src="{{ work.preview.url }}" class="work__preview"></img>
{% else %}
<div class="work__preview">Photo preview</div>
{% endif %}
<h1 class="work__title">{{ work.title }}</h1>
<div class="work__description">{{ work.description }}</div>
</a>
{% endfor %}
</div>
</div>
</img>
{% endblock %}