Block in django doesnt show the another views - python

I'am begginer in Django so please try to understand me.
I have a problem with the blocks in my django project. I created the base.html like this
{% include 'firmy/header.html' %}
<html>
<body>
<h4>Ostatnio dodane</h4>
{% block firmy %}
{% endblock %}
<h4>Kategorie</h4>
{% block kategorie %}
{% endblock %}
</body>
{% include 'firmy/footer.html' %}
</html>
and {%block firmy%} showing me every records what I want from another file but the {%block kategorie%} showing nothing.
in views.py I have the code:
from django.shortcuts import render
from .models import Witryna, Kategorie
from django.utils import timezone
def widok_strony(request):
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
return render(request, 'firmy/widok_strony.html', {'firmy': firmy})
def widok_kategorii(request):
kategorie = Kategorie.objects.all().order_by('glowna')
return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie})
and in urls.py i have the code :
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.widok_strony, name='widok_strony'),
url(r'^$', views.widok_kategorii, name='widok_kategorii'),
]
and on the end models.py
from django.db import models
from django.utils import timezone
class Kategorie(models.Model):
glowna = models.CharField(max_length=150, verbose_name='Kategoria')
class Meta:
verbose_name='Kategoria'
verbose_name_plural='Kategorie'
def __str__(self):
return self.glowna
class Witryna(models.Model):
nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony')
adres_www = models.CharField(max_length=70, verbose_name='Adres www')
slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url')
email = models.CharField(max_length=100, verbose_name='Adres e-mail')
text = models.TextField(max_length=3000, verbose_name='Opis strony')
kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria')
data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji')
class Meta:
verbose_name='Strona www'
verbose_name_plural = 'Strony www'
def publikacja(self):
self.data_publikacji=timezone.now()
self.save()
def __str__(self):
return self.nazwa
and widok_kategorii.html
{% extends 'firmy/base.html' %}
{% block kategorie %}
{% for kategoria in kategorie %}
<p>{{ kategoria.glowna }}</p>
{% endfor %}
{% endblock kategorie %}
Really I don't know where is the problem but when I open the browser on localhost:8000 the I can't see the details from class Kategorie.

You have a huge misconception about how views and URLs work.
A URL can only be served by one view. That view will be entirely responsible for creating the response, which it usually does by rendering a single template. You need to pass all the information for your template from that view.

Related

Slug URL turns into a number when navigating to the next link in django

I tried searching for this problem here but I didn't find anything, I hope someone can help answering or sending a link to a solution on stackoverflow...
I have been creating a blog, and when I click on the post title, it goes to 'post_details.html' and in the URL shows a slug with the post title. Like here:
examplename.com/blog/brooklyn-nets-at-miami-heat-preview/
But when I click to write a comment on the post it takes me to a form page, but the slug title disappear, it just shows the post number. Like this:
examplename.com/blog/3/add-comment
Can someone explain why is this happening? I want to know how to solve this and understand from where it comes this number that shows up.
Post_detail.html
{% block content %}
<h2 class="title">
<a class="post-title" href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Publicado em {{ post.created }} por {{ post.author }}
</p>
{{ post.body|linebreaks }}
<hr>
<h3>Comments</h3>
{% if not post.comments.all %}
Nobody commented yet...Add a comment
{% else %}
Add a comment
{% for comment in post.comments.all %}
{{ comment.name }}
{{ comment.date }}
<br>
{{ comment.body }}
{% endfor %}
{% endif %}
<a class="swen" href="{% url 'blog:list' %}">More Articles</a>
{% endblock %}
urls.py
from unicodedata import name
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path("", views.PostListView.as_view(), name="list"),
path("<slug:slug>/", views.PostDetailView.as_view(), name="detail"),
path("<slug:slug>/add-comment", views.CommentView.as_view(), name="commentview")
]
models.py
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse ('blog:detail', kwargs={"slug":self.slug})
class Meta:
ordering = ("-created",)
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body = models.TextField()
date = models.DateField(auto_now_add=True)
slug = Post.slug
def __str__(self):
return reverse (self.post.title, self.name, self.post.slug)
views.py
from xml.etree.ElementTree import Comment
from django.views.generic import DetailView, ListView, CreateView
from .models import Post, Comment
class PostListView(ListView):
model = Post
class PostDetailView(DetailView):
model = Post
class CommentView(CreateView):
model = Comment
template_name = 'add_comment.html'
fields = '__all__'
you're passing pk which is a type integer as parameter instead of a slug at path name commentview. May be you should check on that.

Django template doesn't display the model items

sorry, I'm very new as a member (and as developer too). I've recently started to work with Django, and I'm trying to display on a page, a list of articles with some elements (title, image, created_at, content), already done in a model.
The views, the template and the path (urls) were bilt too. But when I Run the server and open the browser it only displays the title I passed as the render parameter in the view, not the object (articles = Article.objects.all()), created in the view.
blog/models.py
from email.mime import image
from email.policy import default
from tabnanny import verbose
from turtle import update
from unicodedata import category
from venv import create
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100, verbose_name='name')
description = models.CharField(max_length=250, verbose_name='description')
create_at = models.DateTimeField(auto_now_add=True, verbose_name='created_at')
class Meta:
verbose_name = 'Category'
verbose_name_plural= 'Categories'
def __str__(self):
return self.name
class Article(models.Model):
title= models.CharField(max_length=150, verbose_name="title")
content= RichTextField(verbose_name='Content')
image= models.ImageField(default='null', verbose_name="Image")
public = models.BooleanField(verbose_name="Public?")
user= models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE )
categories = models.ManyToManyField(Category, verbose_name='Category', blank=True)
create_at= models.DateTimeField(auto_now_add=True, verbose_name="Created at")
update_at= models.DateTimeField(auto_now=True, verbose_name="update at")
class Meta:
verbose_name = 'Article'
verbose_name_plural= 'Articles'
def __str__(self):
return self.title
blog/views.py
from django.shortcuts import render
from blog.models import Article, Category
# Create your views here.
def list(request):
articles = Article.objects.all()
return render(request, 'articles/list.html', {
'title' : 'Articles',
'articles': articles
} )
blog/list.html
{% extends 'layouts/layout.html' %}
{% block title %}
{{title}}
{% endblock %}
{% block content %}
<h1 class= "title">{{title}}</h1>
{% for article in articles %}
<article class="article-item">
{% if article.image != 'null' and article.image|length >= 1 %}
<div class="image ">
<img src="{{article.image.url}}" />
</div>
{% endif %}
<div class="data">
<h2>
{{article.title}}
</h2>
<span class="date">{{article.create_at}}</span>
<p>{{article.content|safe}} </p>
</div>
<div class="clearfix"></div>
</article>
{%endfor%}
{% endblock %}
Any help will be very appreciated
It looks like the whole block content is not rendered - Do you have a {% block content %} in the layout.html? You can check in your browser if the source code contains the html of the content block and just the tags are missing

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: 404 Error Appears While Trying to Use Slug in URLs

I am a beginner in Django. Right now, I am learning the framework by building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews.
Right now, I am trying to use slug in URLs. I have successfully used slug in two of my templates, which are index.html and phonemodel.html. However, I am facing issues with the third template, which is details.html.
When I go to http://127.0.0.1:8000/index, I see this page:
When I click on Samsung, I see this page:
Up to this is fine.
But when I click on any phone model, like Galaxy S10, I get 404 error. It looks like this:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/details/galaxy-s10
Raised by: PhoneReview.views.ReviewView
No review found matching the query
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
When I click on Samsung, I am supposed to see the details.html page, which has the review of the phone, along with the news link. Instead, I am getting the 404 error.
Here are my codes of models.py located inside PhoneReview folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.brand_name
def save(self, *args, **kwargs):
self.slug = slugify(self.brand_name)
super().save(*args, **kwargs)
class PhoneModel(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.model_name
def save(self, *args, **kwargs):
self.slug = slugify(self.model_name)
super().save(*args, **kwargs)
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
link = models.TextField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
Here are my codes of urls.py located inside PhoneReview folder:
from . import views
from django.urls import path
app_name = 'PhoneReview'
urlpatterns = [
path('index', views.BrandListView.as_view(), name='brandlist'),
path('phonemodel/<slug:slug>', views.ModelView.as_view(), name='modellist'),
path('details/<slug:slug>', views.ReviewView.as_view(), name='details'),
]
Here are my codes of views.py located inside PhoneReview folder:
from django.shortcuts import render, get_object_or_404
from django.views import generic
from .models import Brand, PhoneModel, Review
class BrandListView(generic.ListView):
template_name = 'PhoneReview/index.html'
context_object_name = 'all_brands'
def get_queryset(self):
return Brand.objects.all()
class ModelView(generic.ListView):
template_name = 'PhoneReview/phonemodel.html'
context_object_name = 'all_model_name'
def get_queryset(self):
self.brand = get_object_or_404(Brand, slug=self.kwargs['slug'])
return PhoneModel.objects.filter(brand=self.brand)
class ReviewView(generic.DetailView):
model = Review
template_name = 'PhoneReview/details.html'
Here are my codes of apps.py located inside PhoneReview folder:
from django.apps import AppConfig
class PhonereviewConfig(AppConfig):
name = 'PhoneReview'
Here are my codes of index.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Brand List
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Brand List Page</h1>
<h2>Here is the list of the brands</h2>
<ul>
{% for brand in all_brands %}
<!-- <li>{{ brand.brand_name }}</li>-->
<li>{{ brand.brand_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of phonemodel.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Phone Model Page
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
<ul>
{% for phonemodel in all_model_name %}
<li>{{ phonemodel.model_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of details.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
<html>
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<html lang="en">
{% block title%}Details{% endblock %}
{% block content %}
<h1>This is the Details Page</h1>
<h2>Review:</h2>
<p>{{ review.review_article }}</p>
<h2>News Link:</h2>
<a href={{ review.link }}>{{ review.link }}</a>
{% endblock %}
</html>
Have I made any mistake in models.py or details.html?
I don't think there is an error in the code here. open Django shell by python3 manage.py shell then run the following query
I guess this will probably give NotFound error because there is no model with slug galaxy-s10
from your_app.models import Review
samsung_s10 = Review.objects.get(slug='galaxy-s10')
print(smasung_s10.slug)

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.

Categories

Resources