admin
personal info: add name
models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
def __str__(self):
return self.title + ' | ' + str(self.author)
__str__
__str__: return self.title + ' | ' + str(self.author)
(inside project folder )
from django.views.generic import ListView, DetailView
from .models import Post
class HomeView(ListView):
model = Post
template_name = 'home.html'
# old views
# def home(request):
# return render(request, 'home.html', {})
.as_view()
from django.urls import path
from .views import HomeView
urlpatterns = [
path('', HomeView.as_view(), name="home"),
]
{% for post in object_list %}
we didn't send context from view, but we can get hold of data with 'object_list' at template
li tag lives inside ul
notice {{ post.author.first_name }}
brings registered name
<h1> Post </h1>
<ul>
{% for post in object_list %}
<li>{{ post.title }} -
{{ post.author.first_name }}{{ post.author.last_name }} <br/>
{{ post.body }}</li>
{% endfor %}
</ul>
DetailView: brings back one record. e.g. One blog post.
class ArticleDetailView(DetailView):
model = Post
template_name = 'article_details.html'
path('article/<int:pk>',
ArticleDetailView.as_view(), name="article-detail"),
{% for post in object_list %}
we didn't send context from view, but we can get hold of data with 'object_list' at template
{% url 'article-detail' post.pk %}
created a link to each 'article_details' pages
home.html
<h1> Post </h1>
<ul>
{% for post in object_list %}
<li><a href="{% url 'article-detail' post.pk %}">
{{ post.title }}</a> -
{{ post.author.first_name }}{{ post.author.last_name }} <br/>
{{ post.body }}</li>
{% endfor %}
</ul>
passing post or object???
article_details.html
<h1>{{ post.title }}</h1>
<small>By: {{ post.author.first_name }}
{{ post.author.last_name }}</small><br>
<hr>
</br>
{{ post.body }}
<br/><br/>
<a href="{% url 'home' %}"> Back </a>
-Bootstrap example
<button type="button" class="btn btn-secondary">Back</button>
-Applied to project
<a href="{% url 'home' %}" class="btn btn-secondary> Back </a>
container pushes everything over.
div class="container"
navbar
inside body tag
{% url 'home' %} -> same as usr_for'function_name'
a class="navbar-brand" href="{% url 'home' %}">Blog</a>
class Post(models.Model):
title_tag = models.CharField(
max_length=255, default='Hello Blog')
article_details.html
{% block title %} {{ post.title_tag }} {% endblock %}
SEO meta tags -> same method!