How to use {{ post.title }} from blog.models into home_app template - django

I want to use the {{ post.title }} and {{ for post in object_list }}
into my home template to show the latest 4 posts, I tried to import from blog.models import Post, but it doesn't work. I guess I'm putting it in the wrong place.
blog.models
from django.db import models
from ckeditor.fields import RichTextField
class Post(models.Model):
title = models.CharField(max_length = 140)
image = models.ImageField(upload_to="media", blank=True)
body = RichTextField(config_name='default')
date = models.DateField()
def __str__(self):
return self.title
home.urls
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
]
home.views
from django.views.generic import TemplateView
from allauth.account.forms import LoginForm
class HomePageView(TemplateView):
template_name = 'home/index.html'
mysite tree look like this
mysite
home
admin
app
models
tests
urls
views
blog
admin
app
models
tests
urls
views

You can override get_context_data and add the latest blog posts to the template context.
from blog.models import Post
class HomePageView(TemplateView):
template_name = 'home/index.html'
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
context['object_list'] = Post.objects.order_by('-date')[:4]
return context

Related

get request in django?

I have problem with django request.I dont know. I tried to do everything, but I got
'blog' object has no attribute 'get'. I want to do mini blog on my website,but it isnt working now. I would like to get all objects from database.(Sorry,If I did something wrong,I am beginner in django and tried to functions for my website) :)
models.py
from django.db import models
# Create your models here.
CHOOSE =[
('Usual','Обычный тариф'),
('Premium','Премиум тариф'),
('Prise','Аукционный')
]
class VDSTARIFS( models.Model):
id = models.CharField(max_length=40, primary_key= True,serialize=True)
name = models.CharField(max_length=20, verbose_name = 'Цены')
choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.')
title = models.CharField(max_length= 15)
def __str__(self):
return str(self.title)
class blog(models.Model):
id = models.CharField(max_length=40, primary_key= True,serialize=True)
message = models.TextField( verbose_name= 'Сообщение блога')
titleblog = models.CharField(max_length=50, verbose_name = 'Название')
img = models.ImageField(upload_to = 'admin/', verbose_name= 'Картинка' )
def __str__(self):
return str(self.titleblog)
def get_all_objects(self): ##maybe I have troubles with it.
queryset = self.__class__.objects.all()
blog.html
{% csrftoken %}
{% for item in message %}
{% endfor %}
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from django.http import HttpResponseRedirect
import os
from polls.models import VDSTARIFS
from polls.models import blog
from django.template.loader import render_to_string
def index_view(request):
#return HttpResponse("<h1>Hello</h1>")
return render(request, "home.html", {})
def about(request):
return render(request, "about.html", {})
def minecraft(request):
return render(request, "minecraft.html",{})
def vds(request):
HTML_STRING = render_to_string("vds.html", context = context1)
return HttpResponse(HTML_STRING)
try:
VDS1 = VDSTARIFS.objects.get(id=0)
name = VDS1.name
except VDSTARIFS.DoesNotExist:
VDS1 = None
context1 = {
'name':name,
'prise':VDS1,
}
def messagesblog(request,self):
HTML_STRING = render_to_string('blog.html')
return HttpResponse(HTML_STRING)
urls.py
from django.contrib import admin
from django.urls import path
from polls import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index_view, name='home'),
path('vds', views.vds, name='vds' ),
path('minecraft', views.minecraft, name='minecraft' ),
path('about', views.about, name='about'),
path('blog', views.blog, name='blog')
]
The actual error is probably caused by the wrong url pattern:
path('blog', views.blog, name='blog')
views.blog refers to the blog model due to:
from polls.models import blog
What you need here is the view not the model, so:
path('blog', views.messagesblog, name='blog')
Then, remove the "self" argument from your messagesblog function.
Use the "render" function from django.shortcuts and provide a context with the blog objects:
def messagesblog(request):
return render(request, "blog.html", {message: blog.objects.all()})
That might solve your problem.
Still, there are some things you could improve.
E.g.: Don't use "id" fields in your model definitions if you don't really, really have to, as this is usually an auto-generated number (BigInt) field.
That's only one tip from an old Django veteran happy to be finally heard. You'll find out much more yourself as you proceed.

In the process of categorising my blogs but keep hitting the wall "Page not found 404"

I am a complete beginner so I apologies for my noobiness explanation. I am in the process of categorising my blogs.
I created a model -> migrated it -> imported in view.py -> Imported the view that I created into urls.py -> and created URL for my new page but when I add the href to other pages (home) it takes me to the error.
My codes:
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
content=models.TextField()
date_posted=models.DateTimeField(default=timezone.now)
author=models.ForeignKey(User, on_delete=models.CASCADE)
category = models.CharField(max_length=100, default='Engineering')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
Views.py:
from .models import Post, Category
class CategoryListView(ListView):
model = Post
template_name= 'blog/category_posts.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 3
urls.py:
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CategoryListView)
path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'),
home.html
{{ post.category }}
In addition to what Arun said.
I think you need to set url_patters in your urls.py. Something like this:
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CategoryListView)
urlpatterns = [
path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'),
]
You should also pass the category in your url, like this
{{ post.category }}
Because your url needs a str parameter category.

NoReverseMatch with generic DeleteView

I cannot figure out why I'm getting NoReverseMatch when trying to use this view. I'd like to get generic views to work because it seems like alot less code to do the same task.
views.py
from django.views.generic import DetailView, ListView, UpdateView, CreateView, DeleteView
from django.urls import reverse_lazy
from .models import *
class ProductDeleteView(DeleteView):
model = Product
success_url = reverse_lazy('homepage_view')
models.py
from django.db import models
from django.urls import reverse
from autoslug import AutoSlugField
class Product(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(null=True, default=None,
unique=True, populate_from='name')
def get_delete_url(self):
return reverse('product_delete_view', args=(self.slug,))
class Meta:
verbose_name_plural = "Products"
def __str__(self):
return self.name
urls.py
from . import views
from django.urls import path, include
from django.views.generic import TemplateView
app_name = "main"
urlpatterns = [
path('product/delete/<slug:slug>/', views.ProductDeleteView.as_view(), name='product_delete_view'),
]
template
<p>
<a class="btn btn-primary" href="{{product.get_delete_url}}">Delete Product</a>
</p>
you should add the app name also in get delete url method
def get_delete_url(self):
return reverse('main:product_delete_view', args=(self.slug,))

TemplateDoesNotExist at /poll/poll/result.html

I get this error TemplateDoesNotExist at /poll/poll/result.html....I think I'm pointing to poll/poll/result.html but how do I point it to poll/result.html
{'Gender': <QuerySet [{'Gender': 'female', 'Diseases': 'Malaria', 'Number': 1}, {'Gender': 'female', 'Diseases': 'cholera', 'Number': 2}
I am new to django but what possibly am I doing wrong here.This is the file structure for template.html: mysite/polls/templates/polls/template.html and for result.html its mysite/polls/templates/polls/result.html
Views.py
from django.views.generic import ListView, CreateView, UpdateView
from django.urls import reverse_lazy
from . models import MyModel
from . forms import MyModelForm
from django.db.models import Count
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views.generic.list import ListView
class CreateMyModelView(CreateView):
model = MyModel
form_class = MyModelForm
template_name = 'poll/template.html'
success_url = 'poll/result.html'
class MyModelListView(ListView):
model = MyModel
def get_queryset(self):
queryset = MyModel.objects.values('Gender', 'Diseases').annotate(Number=Count("Gender"))
return render('poll/result.html', {'Gender': queryset})
urls.py
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
url(r'^$', views.CreateMyModelView.as_view(), name='abc'),
path('poll/result.html', views.MyModelListView.as_view(), name='result'),
]
models.py
from django.db import models
Gender = (
('male', 'MALE'),
('female', 'FEMALE'),
)
Diseases = (
('cholera', 'CHOLERA'),
('hiv', 'HIV'),
('Malaria', 'MALARIA'),
('Typhoid', 'TYPHOID'),
)
class MyModel(models.Model):
Gender = models.CharField(max_length=16, choices=Gender, default='MALE')
Diseases = models.CharField(max_length=16, choices=Diseases, default='MALARIA')
vote = models.IntegerField(default=0)
def __str__(self):
return self.Gender
def __str__(self):
return self.Diseases
result.html
{% extends 'polls/base.html' %}
{% block main_content %}
<h1></h1>
<ul>
{% for choice in Gender %}
<li> {{choice.Gender}} - {{choice.Diseases}} - {{ choice.Number}}</li>
{% endfor %}
</ul>
Vote Again?\\
{% endblock %}
Your template is at "polls/result.html" but you told the view it was "poll/result.html".
(Note, you really shouldn't give your URLs paths ending in "html"; it's not necessary, and it's confusing you. URLs and template locations have nothing to do with each other.)

Having trouble with slug

I was writing a model online shop django app, wanted to incorporate slug in it. Having trouble in opening a page.
This is my model:
from __future__ import unicode_literals
from django.db import models
from django.db.models.signals import pre_save
from django.utils .text import slugify
class Customer(models.Model):
customer_name = models.CharField(max_length=200)
slug = models.SlugField(unique = True)
def __str__(self):
return self.customer_name
def get_absolute_url(self):
return reverse("OnlineShop:order", kwargs={"slug": self.slug})
def pre_save_customer_receiver(sender, instance, *args, **kwargs):
slug = slugify(instance.customer_name)
exists = Customer.objects.filter(slug = slug).exists()
if exists:
slug = "%s-%s" % (slug,instance.id)
instance.slug=slug
pre_save.connect(pre_save_customer_receiver, sender = Customer)
This is my view:
def customer(request):
customer_list = Customer.objects.all()
template_path = 'OnlineShop/customer.html'
context={
'customer_list':customer_list,
}
return render(request,template_path,context)
def order(request,slug):
Customer = Customer.objects.filter(slug=slug)
''' some code from here '''
And my template customer.html:
<h1>List of Customers:</h1>
<ul>
{% for customer in customer_list %}
<li><a href='{% url 'order' customer.slug %}'>{{ customer.customer_name }}<br></li>
{% endfor %}
</ul>
This is my urls.py
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^$',views.customer, name='customer'),
url(r'^customer/(?P<slug>[\w-]+)$',views.order, name='order'),
]
Is the problem in the template? What is wrong?
I hope you've defined your urls.py like below,
from django.conf.urls import url, include
from . import views
onlineshop_patterns = [
url(r'^$', views.customer, name='customer'),
url(r'^customer/(?P<slug>[\w-]+)$', views.order, name='order'),
]
urlpatterns = [
# ...
url(r'^OnlineShop/', include(onlineshop_patterns)),
# ...
]
Read Reverse resolution of URLs and Regex for SlugField.