cant see my blog post on my django website - python

im trying to follow this django tutorial, there a three section on my website called home blog and content.
what should happen, is i click on blog and it list out the blog post i made in the admin and i can click on the post and read what the blog post says, but when i click on blogs nothing shows up, its just blank.
i have already installed apps in settings
i added the url in the url.py folder
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('personal.urls')),
url(r'^blog/', include('blog.urls')),
I went into the models folder and created a model
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
date = models.DateTimeField()
def __str__(self):
return self.title
in my blogs/urls folder i have
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from django.urls import path
urlpatterns = [ path('', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25],
template_name="blog/blog.html")),
path('<int:pk>/', DetailView.as_view(model=Post,
template_name='blog/post.html'))]
in my blog folder i made a new directory called templates and in templates i made another directory called blog and in the folder i made an html file called blog.html and it is in a notepad++. this is what is in that blog.html notepad
{% extends "personal/header.html" %}
{% block content %}
{% for post in obejects_list %}
<h5>{{ post.date|date:"Y-m-d" }}<a href=
"/blog/{{post.id}}"> {{post.title}}</a></h5>
{% endfor %}
{% endblock %}
and i went into admin folder and added
from django.contrib import admin
from blog.models import Post
admin.site.register(Post)

try to add context_object_name to your ListView class like this :
path('', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25],
template_name="blog/blog.html", context_object_name = "posts")),
then in your template do like this :
{% extends "personal/header.html" %}
{% block content %}
{% for post in posts %}
<h5>{{ post.date|date:"Y-m-d" }}<a href=
"/blog/{{post.id}}"> {{post.title}}</a></h5>
{% endfor %}
{% endblock %}

Related

Not able to navigate between two templates in a Django application

I have a ran into a difficulty when navigating between different templates in a Django (v3.2) application. The app is called 'manage_remittance'.
The default landing page (which uses template manage_remittance/templates/manage_remittance/view_remittance.html) for the app should show a list of items (list is not relevant at the moment), and at the top of that list there should be a link, leading to another page in the same app, which would allow to add new items to the list.
The form that is invoked first is here:
manage_remittance/templates/manage_remittance/view_remittance.html
{% extends "root.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% url 'manage_remittance:remittance_add' as remittance_add %}
{% block title %}
VIEW REMITTANCES PAGE
{% endblock title %}
{% block content %}
<div class="list-group col-6">
Click here to add remittance data
</div>
I want to be able to get to another template (manage_remittance/templates/manage_remittance/remittance_add.html), but the {{ remittance_add }} has no value.
In addition, when I specify exact name of the html file (remittance_add.html) in the a href (see above), and click on it, I get a following error:
Using the URLconf defined in sanctions_project.urls, Django tried these URL patterns, in this order:
admin/
[name='login']
login/ [name='login']
logout/ [name='logout']
manage_remittance/ [name='view_remittance']
manage_remittance/ remittance_add/ [name='create_remittance']
^static/(?P<path>.*)$
^media/(?P<path>.*)$
The current path, manage_remittance/remittance_add.html, didn’t match any of these.
What am I doing wrong here?
fragment of urls.py for the project:
urlpatterns = [
path('admin/', admin.site.urls),
path('', login_view, name='login'),
path('login/', login_view, name='login'),
path('logout/', logout_view, name='logout'),
path('manage_remittance/', include('manage_remittance.urls')), # namespace='manage_remittance'
]
urls.py at manage_remittance app:
from .views import (
CreateRemittanceInfo,
RemittanceListView
)
app_name = 'manage_remittance'
urlpatterns = [
path('', RemittanceListView.as_view(), name='view_remittance'),
path('remittance_add/', CreateRemittanceInfo.as_view(), name='create_remittance'),
]
views.py at manage_remittance app:
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views.generic import ListView
from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Remittance
class CreateRemittanceInfo(LoginRequiredMixin, CreateView):
model = Remittance
fields = ['remittance_text']
template_name_suffix = '_add'
class RemittanceListView(ListView):
model = Remittance
template_name = 'manage_remittance/view_remittance.html'
It seems that you have an issue in your urls:
manage_remittance/ remittance_add/ [name='create_remittance']
the name does not match with
manage_remittance:remittance_add
It seems quite simple: in your template, you should display a list, which is not the case. Have a look at Django User Guide: https://docs.djangoproject.com/fr/3.2/ref/class-based-views/generic-display/
It should look like
{% for object in object_list %}
<p>{{object.remittance_text}}</p>
{% endfor %}

html forms are not showing in the template browsing

[solved]
i am trying to make a blog in django and on the github here is the code
i am trying set the html crispy form template in change password option and made some file names password_change_form.html, password_change_done.html etc. but when try to browse http://127.0.0.1:8000/accounts/password_change/done/ or any kind of pages related to password change section it is not showing the crispy form. but login or signup links are showing in crispy form. password change forms are showing in basic django form.
i want to change it into the desired ones.
i made two apps : blogapp and accounts. i am copying the urls below:
blogapp/urls.py:
from django.urls import path
from .views import (BlogappListView,
BlogappPostView,
BlogappCreateview,
BlogappUpdateView,
BlogappDeleteView,
)
urlpatterns = [
path('post/<int:pk>/delete/',BlogappDeleteView.as_view(),name='post_delete'),
path('post/<int:pk>/edit/',BlogappUpdateView.as_view(),name='post_edit'),
path('post/new/', BlogappCreateview.as_view(),name='post_new'),
path('post/<int:pk>/',BlogappPostView.as_view(),name='post_detail'),
path('',BlogappListView.as_view(),name='home'),
]
accounts/urls.py:
from django.urls import path
from .views import SignUpView
urlpatterns = [
path('signup/',SignUpView.as_view(),name='signup')
]
blog_project/urls.py:
from django.contrib import admin
from django.urls import path,include
from django.views.generic.base import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/',include('accounts.urls')),
path('accounts/',include('django.contrib.auth.urls')),
path ('',include('blogapp.urls')),
path('',TemplateView.as_view(template_name='home.html'),name='home')
]
i pur password change forms htmls files under templates/registration folder. here is onehtml file for example:
{% extends 'base.html' %}
{% block title %}Forgot Your Password?{% endblock title %}
{% load crispy_forms_tags %}
{% block content %}
<h1>Forgot your password?</h1>
<p>Enter your email address below, and we'll email instructions for setting
a new one.</p>
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-success" type="submit" value="Send me instructions!">
</form>
{% endblock content %}
this file is named as password_reset_form.html. there are are couple of othe files named password_change_done.html, password_reset_complete.html etc none of the password related files html are not showing ....all the urls are showing the basic django template.
i just can't figure out what am i missing and or what did i wrong? password change suppose to show the html form....not in django basic form.
please let me know where is my mistake.thanx in advance
I solved it. I changed templates directory from blogapp to project folder directory where manage.py exists. And everything else I did right. And it took a lot of time to figure out which is silly. Thanx any way... kept the answer if someone need this

Django Template - Cannot iterate throught this list and get menu item

i have one project andromeda where is 2 apps. 1 is blog and seccond one is blogmenu
but when I want to get information from the blog app there is no problem and i can get all information. but when I want to get a menu item from blogmenu I'm getting now error but there is empty navigation bar.
blogmenu urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('', include('blogmenu.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
blogmenu views.py
from django.shortcuts import render
def Blog_Menu(request):
Menu_items = Menu.objects.all()
template_name = 'front/index.html'
return render(request, template_name, {"Menu_items":Menu_items})
blogmenu models.py
from django.db import models
class Menu(models.Model):
Menu_name = models.CharField(max_length=100,blank=True)
Menu_slug = models.SlugField(name="სლაგი",blank=True)
Menu_image = models.ImageField(upload_to="menuimages")
Menu_url = models.CharField(name="url",max_length=100,blank=True,null=True)
class Meta:
verbose_name = "მენიუ"
def __str__(self):
return self.Menu_name
sample html template code
{% for menu in Menu_items %}
<li class="main-menu-item">
just text
</li>
{% endfor %}
When iteration items in loop you should post something. You can do the below in your template.
{% for menu in Menu_items %}
<li class="main-menu-item">
{{ menu.Menu_name }}
</li>
{% endfor %}
Seems to me that you just forgot to use the object from the for loop.
This is probably what your looking for:
{% for menu in Menu_items %}
<li class="main-menu-item">
{{ menu.Menu_name }}
</li>
{% endfor %}
If this isn't working either then I would suggest putting a print(Menu_items) after you make the query in your blogmenu views.py and see if your getting your data there.
Also don't forget to import your model in your views.py.

loading images by list view in django template

I am trying to render by django template with photos saved in database by using listview so they can act like thumbnails like that of amazon.com but images are not loading
{% for offer in offer_details %}
{% if offer == None %}
<img src="{% static "pics/s7.jpg" %}" class="im">
{% else %}
<img src="{{offer.photo.url}}">
{% endif %}
{% endfor %}
views.py
class Index(ListView):
context_object_name = 'offer_details'
model = models.Offer_discription
template_name = "index.html"
from django.contrib import admin
from django.urls import path,include
from interface import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls, name="adi"),
path("",views.Index.as_view(), name="index"),
path("interface/",include("interface.urls")),
path("logout/",views.user_logout, name="logout"),
path("special", views.special,name="special"),
path("<int:pk>/", views.OfferDetailView.as_view(), name=" OfferDetailView")
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I was not adding that last line of code and last two imports

How to embed the results of my django app inside a template using something like {% include "app" %}?

So far I have been able to Create a project and setup a Homepage. So far I have had success with styling the page and getting my nav areas setup. I have also created an app that pulls a list of category names from my database and displays it in a right-justified list. When I point my browser to the app url, it works perfectly, but when I try to include the view in my project it displays the base panel with an error, and the dictionary I passed to the view does not appear to be available.
This is what I get when I load the home url localhost:8000/ in my browser:
This is what I get when I load the app url localhost:8000/categories/ in my browser:
Why am I not able to push the results of my app into my template? Both appear to work but not together?
base_right_panel.html
{% block content %}
<div style="float: right;">
<div id="base_categories" style="margin: 10px; padding-bottom: 10px;">
{% block base_categories %}
{% include "base_categories.html" %}
{% endblock %}
</div>
</div>
{% endblock %}
base_categories.html
{% block content %}
<div class="section" style="float: right;">
<h4 class="gradient">Category List</h4>
<ul>
{% if categories %}
{% for category in categories %}
<li>{{ category.title }}</li>
{% endfor %}
{% else %}
<p>no data! {{ categories|length }}</p>
{% endif %}
</ul>
</div>
{% endblock %}
CategoryList/views.py
from django.views.generic import TemplateView
from CategoryList.models import CategorylistCategorylist #<-- Changed to match inspectdb result
class IndexView(TemplateView):
template_name="base_categories.html" #<-- Changed name from index.html for clarity
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context["categories"] = CategorylistCategorylist.objects.all()
return context
CategoryList/models.py
from django.db import models
class CategorylistCategorylist(models.Model): #<-- Changed to match inspectdb
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255L, unique=True)
base_url = models.CharField(max_length=255L, unique=True)
thumb = models.ImageField(upload_to="dummy", blank=True) #<-- Ignored inspectdb's suggestion for CharField
def __unicode__(self):
return self.name
# Re-added Meta to match inspectdb
class Meta:
db_table = 'categorylist_categorylist'
CategoryList/urls.py
from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django.conf import settings
from CategoryList import views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='base_categories'),
)
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns
MySite/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from home import views as home_view
from CategoryList import views as index_view
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', home_view.HomeView.as_view(), name="home"),
url(r'^categories/$', index_view.IndexView.as_view(), name='base_categories'),#include('CategoryList.urls')),
url(r'^admin/', include(admin.site.urls)),
#url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
)
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns
I have another open question which has the relevant code examples but the question differs from what I am asking here.
Is there a simple way to display mysql data in Django template without creating an app?
You need to add the category queryset to your context in your HomeView. Remember, the view uses the templates to build the response - including a template that you also use in a different view (IndexView) does not cause any interaction with IndexView.
HomeView produces its response by rendering a template. If that template uses {% include %} tags to pull in pieces of other templates, those pieces will be rendered using the context established by HomeView. Nothing you do in IndexView has any effect on HomeView, and vice versa.
Continuing to reason by analogy to string interpolation, pretend your templates are global string variables instead of files on disk. Your situation is something like this:
base_categories = "My categories are: %(categories)s."
base_right_panel = "This is the right panel. Here are other fields before categories."
Using the {% include %} tag is something like string concatenation:
base_right_panel = base_right_panel + base_categories
Then your two views are analogous to this:
def home_view(request):
context = {}
return base_right_panel % context
def index_view(request)
context = {'categories': ['a', 'b', 'c']}
return base_categories % context
Unless you add the categories queryset to the context in HomeView, it will not be available to the template engine when rendering the response.
Your HomeView class should include the get_context_data method that you currently have in your IndexView. I am not sure you actually need IndexView at all, unless you want to have something that serves that page with just the categories list.

Categories

Resources