Django - Как перенаправлять на данные модели
Как при нажатии на ссылку которая ведет на адрес модели открывать нужную страницу? Т.е у меня есть модель которую я вывел как ссылку и при нажатии на модель должен открываться общий для всех ссылок этой модели, html файл.
Пытался сделать так, но не вышло.
urls.py
from django.urls import path
from .models import *
from . import views
app_name = 'forum'
urlpatterns = [
path('', views.index, name='index'),
path(Section.section_url, views.sections, name='sections')
]
models.py
from django.contrib.auth.models import User
class Section(models.Model):
class Meta:
db_table = "section"
verbose_name_plural = 'Разделы'
verbose_name = 'Раздел'
section_title = models.CharField(max_length=200)
section_url = models.CharField(max_length=50)
section_description = models.TextField()
def __str__(self):
return self.section_title
class Discussions(models.Model):
title = models.CharField(max_length=50)
text = models.TextField()
description = models.CharField(max_length=200)
section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
date = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
return str(self.id) + '.' + self.title + self.description
class Meta:
verbose_name_plural = 'Обсуждения'
verbose_name = 'Обсуждение'
views.py
from django.shortcuts import get_object_or_404, render
from .models import *
def index(request):
sections = Section.objects.order_by('section_title')
return render(request , 'index.html', {'section_list': sections})
def sections(request):
return render(request, 'section.html')
index.html
{% block page %}
<article>
<h1>Разделы</h1>
{% if section_list %}
<ul>
{% for section in section_list %}
<li>
<a href="{{ section.section_url }}" class="viewlink">{{ section.section_title }}</a>
</li>
{% endfor %}
</ul>
{% endif %}
</article>
{% endblock %}