ayy24
ayy24

Reputation: 23

Cannot see blog posts in index.html

I am trying to make a simple blog website. I have created my files and models. The page shows up fine, and the admin works. I have created a few posts in the admin for testing. However, the blogs do not reflect on index.html from the admin page. I included the app in settings.py. All the other pages work, so I don't think the issue is with the file structure.

models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils import timezone

class Todo(models.Model):
    title = models.CharField(max_length=100)
    memo = models.TextField(blank=True)
    created = models.DateTimeField(auto_now_add=True)
    datecompleted = models.DateTimeField(null=True, blank=True)
    important = models.BooleanField(default=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title


class Post(models.Model):
    title = models.CharField(max_length=200, default='', unique=True)
    first_name = models.CharField(max_length=50, default='', editable=False)
    last_name = models.CharField(max_length=50, default='', editable=False)
    body = models.TextField(default='')

def __str__(self):
    return self.title

urls.py (Project)

from django.contrib import admin
from django.urls import path, include
from todo import views


urlpatterns = [
    path('admin/', admin.site.urls),


# Auth
path('signup/', views.signupuser, name="signupuser"),
path('logout/', views.logoutuser, name='logoutuser'),
path('loginuser/', views.loginuser, name='loginuser'),



# Todos
path('', views.home, name='home'),
path('', include('todo.urls')),
path('index/', views.index, name="index"),
path('detail/', views.detail, name="detail"),
path('current/', views.currenttodos, name="currenttodos"),
path('create/', views.createtodo, name='createtodo'),
path('completed/', views.completedtodos, name="completedtodos"),
path('todo/<int:todo_pk>', views.viewtodo, name='viewtodo'),
path('todo/<int:todo_pk>/complete', views.completetodo, name='completetodo'),
path('todo/<int:todo_pk>/delete', views.deletetodo, name='deletetodo'),
path('hotel/', views.hotel, name="hotel"),
path('things/', views.things, name="things"),
path('restaurant/', views.restaurant, name="restaurant"),
path('review/', views.review, name="review"),
path('blog/', views.blog, name="blog"),

]

urls.py (App)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.BlogListView.as_view(), name='index'),
    path('todo/<int:pk>', views.BlogDetailView.as_view(), name='detail'),
]

views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.contrib.auth import login, logout, authenticate
from .forms import TodoForm
from .models import Todo, Post
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.views import generic
from django.views.generic import ListView, DetailView

class BlogListView(ListView):
    model = Post
    template_name = 'index.html'


class BlogDetailView(DetailView):
    model = Post
    template_name = 'detail.html'


def index(request):
    return render(request, 'todo/index.html')


def detail(request):
    return render(request, 'todo/detail.html')

def home(request):
    return render(request, 'todo/home.html')


def signupuser(request):
    if request.method == 'GET':
        return render(request, 'todo/signupuser.html', {'form': UserCreationForm()})
    else:
        if request.POST['password1'] == request.POST['password2']:
            try:
                user = User.objects.create_user(
                    request.POST['username'], password=request.POST['password1'])
                user.save()
                login(request, user)
                return redirect('currenttodos')
            except IntegrityError:
                return render(request, 'todo/signupuser.html', {'form': UserCreationForm(), 'error': 'That username has already been taken. Please choose another username.'})
        else:
            return render(request, 'todo/signupuser.html', {'form': UserCreationForm(), 'error': 'Passwords did not match'})


def loginuser(request):
    if request.method == 'GET':
        return render(request, 'todo/loginuser.html', {'form': AuthenticationForm()})
    else:
        user = authenticate(
            request, username=request.POST['username'], password=request.POST['password'])
        if user is None:
            return render(request, 'todo/loginuser.html', {'form': AuthenticationForm(), 'error': 'Username and password did not match'})
        else:
            login(request, user)
            return redirect('currenttodos')


@login_required
def logoutuser(request):
    if request.method == 'POST':
        logout(request)
        return redirect('home')


@login_required
def currenttodos(request):
    todos = Todo.objects.filter(user=request.user, datecompleted__isnull=True)
    return render(request, 'todo/currenttodos.html', {'todos': todos})


@login_required
def createtodo(request):
    if request.method == 'GET':
        return render(request, 'todo/createtodo.html', {'form': TodoForm()})
    else:
        try:
            form = TodoForm(request.POST)
            newtodo = form.save(commit=False)
            newtodo.user = request.user
            newtodo.save()
            return redirect('currenttodos')
        except ValueError:
            return render(request, 'todo/loginuser.html', {'form': TodoForm(), 'error': 'Bad data passed in.'})


@login_required
def viewtodo(request, todo_pk):
    todo = get_object_or_404(Todo, pk=todo_pk, user=request.user)
    if request.method == 'GET':
        form = TodoForm(instance=todo)
        return render(request, 'todo/viewtodo.html', {'todo': todo, 'form': form})
    else:
        try:
            form = TodoForm(request.POST, instance=todo)
            form.save()
            return redirect('currenttodos')
        except ValueError:
            return render(request, 'todo/viewtodo.html', {'todo': todos, 'form': form, 'error': "Bad info"})


@login_required
def completetodo(request, todo_pk):
    todo = get_object_or_404(Todo, pk=todo_pk, user=request.user)
    if request.method == 'POST':
        todo.datecompleted = timezone.now()
        todo.save()
        return redirect('currenttodos')


@login_required
def deletetodo(request, todo_pk):
    todo = get_object_or_404(Todo, pk=todo_pk, user=request.user)
    if request.method == 'POST':
        todo.delete()
        return redirect('currenttodos')


@login_required

def completedtodos(request):
    todos = Todo.objects.filter(
        user=request.user, datecompleted__isnull=False).order_by('-datecompleted')
    return render(request, 'todo/completedtodos.html', {'todos': todos})


def hotel(request):
    return render(request, 'todo/hotel.html')


def things(request):
    return render(request, 'todo/things.html')


def restaurant(request):
    return render(request, 'todo/restaurant.html')


@login_required
def review(request):
    return render(request, 'todo/review.html')


@login_required
def blog(request):
    return render(request, 'todo/blog.html')

admin.py

from django.contrib import admin
from .models import Todo, Post


class TodoAdmin(admin.ModelAdmin):
    readonly_fields = ('created',)


admin.site.register(Todo, TodoAdmin)
admin.site.register(Post)

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Blog</title>
</head>

<body>
    <header>
        <h1> <a href="">My Blog</a> </h1>
    </header>
    <div class="container">
        {% block content %}
        {% for i in object_list %}
        <div class="article">
            <h3><a href="{% url 'detail' i.pk %}">{{ i.title }}</a></h3>
            <p>{{ i.body }}</p>
        </div>
        {% endfor %}
        {% endblock content %}
    </div>
</body>

</html>

detail.html

{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
    <title>Blog</title>
</head>

<body>
    <header>
        <h1> <a href="">Blog</a> </h1>
    </header>
    <div class="container">
        {% block content %}
        <div class="details">
            <h2>{{ post.title }}</h2>
            <p>{{ post.body }}</p>
        </div>
        {% endblock content %}
    </div>
</body>

</html>

Upvotes: 0

Views: 53

Answers (1)

Daniel Oram
Daniel Oram

Reputation: 8411

Your index view function isn't sending anything for object_list to the template.

def index(request):
    # will get every post
    posts = Post.objects.all()
    return render(request, 'todo/index.html', {'object_list': posts})

Upvotes: 4

Related Questions