Django blank page - python

This is my index.html file:
{% extends "base_site.html" %}
{% block content %}
{% if info %}
<ul>
{% for object in info %}
{{ Hello }}
{% endfor %}
</ul>
{% else %}
<p>No objects are available.</p>
{% endif %}
{% endblock %}
This is my views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from notendur.models import *
from django.views import generic
class IndexView(generic.ListView):
template_name = 'notendur/index.html'
context_object_name = "info"
def get_queryset(self):
"""Return the last five published polls."""
return Information.objects.all()
This is my models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Information(models.Model):
title = models.CharField(max_length = 200)
body = models.TextField()
date = models.DateTimeField()
def __unicode__(self):
return self.title
class InformationChild(models.Model):
information = models.ForeignKey(Information)
child_text = models.CharField(max_length = 200)
def __unicode__(self):
return self.child_text
When I start the server, however, nothing appears. This has to be some url-link issue, because the else clause doesn't even activate. Perhaps you want urls.py as well?
Let me know if you need further information.

The error is not in the use of info, it's in what's inside the for loop: {{ Hello }} is not an item in the context. Use {{ object.title }}, for example.

Related

When I access the page, nothing appears

I want to use the following code to filter the data in models.py in views.py and output the Today_list to today.html, but when I open this url, nothing is displayed. What is the problem?
class Post(models.Model):
created =models.DateTimeField(auto_now_add=True,editable=False,blank=False,null=False)
title =models.CharField(max_length=255,blank=False,null=False)
body =models.TextField(blank=True,null=False)
def __str__(self):
return self.title
views.py
from Todolist import models
from django.views.generic import ListView
from django.utils import timezone
class TodayView(ListView):
model = models.Post
template_name ='Todolist/today.html'
def get_queryset(self):
Today_list= models.Post.objects.filter(
created=timezone.now()).order_by('-id')
return Today_list
todaylist.html
{% extends "Todolist/base.html" %}
{% block content %}
{% for item in Today_list %}
<tr>
<td>{{item.title}}</td>
</tr>
{% endfor %}
{% endblock %}
urls.py
urlpatterns=[
path('today/' ,views.TodayView.as_view() ,name='today')
]
use get_context_data to add Today_list to context
ref : https://docs.djangoproject.com/en/4.1/ref/class-based-views/generic-display/
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Today_list'] = self.get_queryset()
return context
or you can simply use in template model.name_list in your case it will be post_list instead of today_list
{% extends "Todolist/base.html" %}
{% block content %}
{% for item in post_list %}
<tr>
<td>{{item.title}}</td>
</tr>
{% endfor %}
{% endblock %}
problem is where you want objects that created today, but your queryset filter just right now, not today.
So to achieve today's posts, you can do this:
from django.utils import timezone
def get_queryset(self):
Today_list = models.Post.objects.filter(
created__gte=timezone.now().replace(hour=0, minute=0, second=0),
created__lte=timezone.now().replace(hour=23, minute=59, second=59)
).order_by('-id')
return Today_list
this queryset returns objects that have been created today.

I need help in django

I want to print First semester's Subjects in First Semester & Second semester's Subjects in Second Semester and so on. See this pic
cick in image here
Maybe there is some logic in views.py that Im not having on my mind rn.Can someone help me in this logic and how to render it in semester.html page
My code is here.
models.py
from django.db import models
from django.db.models.base import ModelState
# Create your models here.
class Course(models.Model):
faculty = models.CharField(max_length=100)
class Semester(models.Model):
sem = models.CharField(max_length=100)
faculty = models.ForeignKey(Course, on_delete=models.CASCADE)
def __str__(self):
return F"Semester {self.sem} at Faculty {self.faculty}"
class Subject(models.Model):
faculty = models.ForeignKey(Course, on_delete=models.CASCADE)
sem = models.ForeignKey(Semester, on_delete=models.CASCADE)
subject_name = models.CharField(max_length=100)
def __str__(self):
return str(self.id)
views.py
from django.shortcuts import render
from django.views import View
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField
from django import forms
from django.utils.translation import gettext, gettext_lazy as _
from .forms import CustomerRegistrationForm
from .models import Course, Semester, Subject
# Create your views here.
def home(request):
return render(request, 'app/home.html')
def faculty(request):
course = Course.objects.all()
return render(request, 'app/faculty.html', {'course':course})
class SemesterView(View):
def get(self, request,id):
obj = Course.objects.get(id=id)
print(obj)
semobj = Semester.objects.filter(faculty=obj)
print(semobj)
subobj = Subject.objects.filter(faculty=obj)
print(subobj)
return render(request, 'app/semester.html', {'obj':obj, 'semobj':semobj, 'subobj':subobj})
semester.html
{% extends 'app/base.html' %}
{% load static %}
{% block semester %}
<div class="bsc-csit">
<div class="container">
<div class="row" style="margin-top:90px; padding-top:20px;">
{% for so in semobj %}
<div class="col-md-3">
<div class="bsccsit-box">
<h3 style="color: black">{{so.sem}}</h3>
<ul>
{% for suo in subobj %}
<li>1.{{suo.subject_name}}</li>
{% endfor %}
</ul>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock semester %}
Try replacing the following in your template:
{% for subject in so.subject_set.all %}
<li>{{ forloop.counter }}. {{subject.subject_name}}</li>
{% endfor %}
You can get all Subject's from a specific semester via subject_set.all.
You can also use {{ forloop.counter }} to provide a enumerative number with the associated subject.

Not redirecting from createView form to Home

I am learning fresh django development. Working on a blog project I am facing a issue that, while publishing a new blog, that doesn't redirects to home/blogs page. I tried to manually to go home It says,
OperationalError at /blog/
no such column: App_Blog_blog.author_id
I tried to debug several times, searched in documentation can't get away with this author_id. These are my codes:
Views.py
class CreateBlog(LoginRequiredMixin, CreateView):
model = Blog
template_name = 'App_Blog/create_blog.html'
fields = ('blog_title', 'blog_content', 'blog_image',)
def form_valid(self, form):
blog_obj = form.save(commit=False)
blog_obj.author = self.request.user
title = blog_obj.blog_title
blog_obj.slug = title.replace(" ", "-") + "-" + str(uuid.uuid4())
blog_obj.save()
return HttpResponseRedirect(reverse('index'))
class BlogList(ListView):
context_object_name = 'blogs'
model = Blog
template_name = 'App_Blog/blog_list.html'
Views.py of main project file
def index(request):
return HttpResponseRedirect(reverse('App_Blog:blog_list'))
urls.py
from django.urls import path
from App_Blog import views
app_name = 'App_Blog'
urlpatterns = [
path('', views.BlogList.as_view(), name='blog_list'),
path('write/', views.CreateBlog.as_view(), name='create_blog'),
]
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Blog(models.Model):
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='post_author')
blog_title = models.CharField(max_length=264, verbose_name="Put a Title")
slug = models.SlugField(max_length=264, unique=True)
blog_content = models.TextField(verbose_name="What is on your mind?")
blog_image = models.ImageField(
upload_to='blog_images', verbose_name="Image")
publish_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.blog_title
create_blog.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title_block %}
Write a Blog
{% endblock title_block %}
{% block body_block %}
<h2>Start Writing:</h2>
<form method="POST">
{{ form | crispy }}
{% csrf_token %}
<br>
<button type="button" class="btn btn-success btn-sm">Publish</button>
</form>
{% endblock body_block %}
blog_list.html
{% extends 'base.html' %}
{% block title_block %} Home {% endblock %}
{% block body_block %}
{% for blog in blogs %}
<h3>{{blog.blog_title}}</h3>
<h6>{{blog.publish_date}}</h6>
{% endfor %}
{% endblock %}
Create Blog form:
Error showing on site:

django templates help,upside down

I am trying to build my blog using Django 1.8 however I do not know how can I order the blogs. See the image
I want to display the 'earliest' at the bottom and the 'latest' at the top. Here is my
index.html
{% extends 'layouts/base.html' %}
{% block title %}
Homepage - {{ block.super }}
{% endblock title %}
{% block content %}
<center>
{% for blog in blogs %}
<h2><a href="{% url 'blog_detail' slug=blog.slug %}">
{{ blog.name }}
</a></h2>
<p>{{ blog.description }}</p>
{% endfor %}
</center>
{% endblock content %}
models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.utils import timezone
class blog(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
slug = models.SlugField(unique=True)
date_time = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.name
def get_image_path(instance, filename):
return '/'.join(['blog_images', instance.bupimg.slug, filename])
class Upload(models.Model):
bupimg = models.ForeignKey(blog, related_name="uploads")
image = models.ImageField(upload_to=get_image_path)
views.py
from django.shortcuts import render
from blogging.models import *
def index(request):
blogs = blog.objects.all()
return render(request, 'index.html', {
'blogs':blogs,
})
def blog_detail(request, slug):
article = blog.objects.get(slug=slug)
uploads = article.uploads.all()
return render(request, 'blogs/blog_detail.html', {
'article': article,
'uploads': uploads,
})
How can I move the blog title 'earliest' to the downside ,'latest' on top side? I need let the latest blog shows on the top.
You are not sorting the blogs, they come in a random order. Try changing the line
blogs = blog.objects.all()
to
blogs = blog.objects.order_by('-date_time')
The minus (-) denotes descending sort, ie. from the latest to the oldest.

django rendering template issue

I'm just built my django project but have some problem. I want to display title that is in Academy. When I run python manage.py runserver everything is okay but the title is not displayed. I don't know what the problem is.
class.html
{% extends "base.html" %}
{% block content %}
<div>
<div style="margin-top: 200px;">
</div>
{% for academy in academys %}
<h3>{{ academy.title }}</h3>
{% endfor %}
</div>
{% endblock %}
urls.py
...
url(r'^academy/class', 'academy.views.class', name='class'),
views.py
from django.shortcuts import render, Http404
from .models import Academy
def class(request):
template = 'academy/class.html'
try:
academys = Academy.objects.all()
context = {'academy': academys}
except Academy.DoesNotExit:
raise Http404
if request.user.is_authenticated():
return render(request, template, context)
else:
return HttpResponseRedirect("/account/login/")
models.py
...
class Academy(models.Model):
title = models.CharField(max_length=50)
def __unicode__(self):
return self.title
Your context dictionary key is incorrect. Instead of
context = {'academy': academys}
type
context = {'academys': academys}
You've passing 'academy' in your context not 'academys'
context={'academys ': academys}

Categories

Resources