Tuesday, April 22, 2025

Django To-Do - Redirects in Django

You are advised to check corresponding YouTube video at the end of this article.

Ok, let's create link to Django Admin in header.html


<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>

  </head>
  <body>
    {% block navigation  %}
    <ul>
      <li><a href="{% url 'index' %}">Home</a></li>
      <li><a href="">New Post</a></li>
      <li><a href="{% url 'admin' %}">Admin</a></li>
    </ul>
    {% endblock %}
    <hr>

Which means that local ulrs.py for our todo app demands attention:


from django.urls import path
from .import views

urlpatterns = [
    path('', views.index, name='index'),
    path('details/<int:id>', views.details, name='details'),
    path('admin/', views.admin, name="admin"),
]

Having a route is not enough, we must create function in views.py that will activate redirection in this case:


from django.shortcuts import render, redirect
from .models import Posts

def index(request):
    all_posts = Posts.objects.all()[:10]
    context = {'all_posts' : all_posts}
    return render (request, 'index.html', context)

def details(request, id):
    one = Posts.objects.get(id=id)
    context = {'one' : one}
    return render (request, 'details.html', context)

def admin(request):
    response = redirect('admin')
    return response

Now if we click on Admin in our navigation, redirect will be activated:

Also, we can put link to home page (or any other link) to the botom of details.html page, or even in footer.html, if you prefer that more.


{% extends 'base.html' %}

{% block details %}
<ul>
  <li>{{ one.id }}</li>
  <li>{{ one.title }}</li>
  <li>{{ one.text }}</li>
  <li>{{ one.created }}</li>
</ul>

<a href="{% url 'index' %}">Home</a>

{% endblock %}

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...