Skip to content

Instantly share code, notes, and snippets.

@wsvincent
Last active July 26, 2018 18:54
Show Gist options
  • Save wsvincent/ddde820267d70f705652d6a7cb25a435 to your computer and use it in GitHub Desktop.
Save wsvincent/ddde820267d70f705652d6a7cb25a435 to your computer and use it in GitHub Desktop.
Django slugs ex w/in a "courses" app
{% extends 'base.html' %}
{% block content %}
<div class="container">
<h2>{{ object.title }}</h2>
<p>Author: {{ object.author}}</p>
<p>Description: {{ object.description }}</p>
<p>Sections:</p>
<ul>
{% for section in course.sections.all %}
<li>{{ section.title }}</li>
{% endfor %}
</ul>
</div>
{% endblock content %}
{% extends 'base.html' %}
{% block title %}Courses{% endblock %}
{% block content %}
<div class="container">
<h1 class="courses">Courses</h1>
{% if object_list %}
{% for course in object_list %}
<div>
<h2><a href="{% url 'course_detail' course.slug %}">{{ course.title }}</a></h2>
<p>Author: {{ course.author }}</p>
<p>Description: {{ course.description }}</p>
</div>
{% endfor %}
{% else %}
<p>No courses!</p>
{% endif %}
</div>
{% endblock content %}
from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
class Course(models.Model):
title = models.CharField(max_length=255)
description = models.CharField(max_length=255)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
slug = models.SlugField(default='')
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Course, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('course_detail', kwargs={'slug': self.slug})
from django.urls import path
from .views import CourseListView, CourseDetailView
urlpatterns = [
path('', CourseListView.as_view(), name='course_list'),
path('<slug:slug>/', CourseDetailView.as_view(), name='course_detail'),
]
from django.views.generic import ListView, DetailView
from .models import Course
class CourseListView(ListView):
model = Course
template_name = 'course_list.html'
class CourseDetailView(DetailView):
model = Course
template_name = 'course_detail.html'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment