Summary:
I’m writing a Django web app whose purpose is to showcase a writing sample (a ‘post mortem’) which is basically like a blog post for all intents and purposes. Django is not serving the content and I am not sure why. The problem I figure is with either my views.py or template (copied below). I don’t think the issue is with my models or urls.py but I included them anyways.
Details:
This is my second attempt at getting my Django project to serve this template properly. In my prior first attempt, I encountered a similar issue:
Django not serving text content (First attempt)
There in that question, another SO member answered by identifying three mistakes I was making. The problem there was that I was missing a for loop inside my template, I was missing an all() class method inside my views.py and the context dictionary key value pair in views.py was not pluralized.
Those issues have been resolved however my new issue involves Django serving a blank template when I am expecting the Lorem Ipsum content to show.
Django should be pulling all the class objects from my models.py and then be sending them to the alls/landings.html. I am expecting the title, publication date, image and body content to render on my landing page. But instead, my ‘mortems’ app content (a blog post) isn’t showing on the landing page. The only thing that shows is the heading. To illustrate so you can see what I see, here is what my landing page looks like now:
Based on what you people see below, who can tell me what is wrong with my views / landings.html template?
The full source code can be found on my GitHub page. Here is a snapshot of the state of my project (tagged as v0.6.0).
What follows are the code samples where I suspect my issue exists.
Here is my latest views.py:
from django.shortcuts import redirect, render, get_object_or_404
from mortems.models import Mortem
def mortems(request):
mortems = Mortem.objects.all().order_by('-pub_date')
context = {'mortems':mortems}
return render(request, 'alls/landings.html', context)
Here is my templates/alls/landings.html:
{% load static %}
<html>
<head>
<title> BLOG </title>
<style> </style>
<!-- <link rel="stylesheet" href="{% static 'redactors/style.css' %}"> -->
</head>
<body>
{% block content %}
<h1> BLOG POST:</h1>
{% for mortem in mortems %}
<h1>{{ mortem.title }}</h1>
<h4>Date: {{ mortem.pub_date_preference }}</h4>
<br />
Image: <img src="{{ mortem.image.url }}" class="img-responsive center-block" style="max-height:300px;" />
<br />
<!-- Body text should go here : -->
Body Text:
<p>{{ mortem.body|safe }}</p>
<br />
<br />
{% endfor %}
{% endblock %}
</body>
</html>
Here my project’s main 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('redactors.urls')),
path('', include('counters.urls')),
path('', include('mortems.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is my app’s (mortems) urls.py:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.mortems, name='mortems'),
]
Here is my app’s models.py:
from django.db import models
import datetime
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
# Create your models here.
class Mortem(models.Model):
title = models.CharField(max_length=161)
pub_date = models.DateTimeField()
image = models.ImageField(upload_to='media/')
body = models.TextField()
now = datetime.datetime.now()
def __str__(self):
return self.title
def pub_date_preference(self):
# a = self.pub_date.timezone.now("US")
b = self.pub_date.strftime("%A %d %B %Y # %-I:%M:%S %p")
# c = pytz.timezone("US")
return (b)
def summary(self):
return self.body[:1024]
You are using the same path for views.home in redactors.urls and views.mortems in mortems.urls i.e '/'
CC_Redact_Iter3/urls.py you configured in this order
urlpatterns = [
#Django serves urls in the order you gave
path('admin/', admin.site.urls), #1st
path('', include('redactors.urls')), #2nd
path('', include('counters.urls')), #3rd
path('', include('mortems.urls')), #4th
]
redactors/urls.py
urlpatterns = [
path('', views.home, name='home'), #here you have to change the home path
path('alls/results', views.results, name='results'),
]
mortems/urls.py
urlpatterns = [
path('', views.mortems, name='mortems'), #As you can see views.home is also having same path so change the path for home
]
In your case
def home(request):
if 'ccEntry' in request.GET:
number = request.GET['ccEntry']
redacted_num = 'xxxx xxxx xxxx {}'.format(number[-4:])
return render(request, 'alls/results.html', {'number':number, 'redacted_num':redacted_num})
else:
return render(request, 'alls/landings.html') #this is being rendered instead mortem
Change your CC_Redact_Iter3/urls.py and redactors/urls.py as shown below
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('mortems.urls')),
path('', include('redactors.urls')),
path('', include('counters.urls')),
]
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns = [
path('home/', views.home, name='home'), #here you have to change the home path
path('alls/results', views.results, name='results'),
]
And the date format in you mortems/models.py is Invalid (%-I)
def pub_date_preference(self):
# a = self.pub_date.timezone.now("US")
b= self.pub_date.strftime("%A %d %B %Y # %I:%M:%S %p") #try something like this
# c = pytz.timezone("US")
return (b)
Courtesy of #MeL in the comments, the solution is to include ‘mortems’ as the first argument inside my path() function inside the mortems app’s urls.py. This file looks like this now:
urlpatterns = [
path('mortems', views.mortems, name='mortems'),
]
Now when I navigate to http://127.0.0.1:8000/mortems, the landings.html template renders exactly as intended, with all the content present. To see, here is my mortems page now:
So that is the solution I guess. But I remain flummoxed and curious: why? With the path parameter empty ’’, I’d expect Django to serve the landings.html template on the home page / landing page at this location: http://127.0.0.1:8000/. Django serves the template but all the content is missing. Only after adding a string as an argument the content shows. Why is that?
If someone could kindly answer why, I’d be happy to update this answer here with more information.
Related
thanks for taking a moment to try and help me out. Haven't done much coding in many years, switched careers for some reason.. Decided to play with Django, everything was going fine, and I can't figure out this URL/slug problem. I've got some links, first.
It's explained on their GitHub rep but I can't figure it out. I've also used this handy site and am still in the dark.
I Know its relatively simple, just having a hard time finding up to date code and books, and I've been frustrating myself on it for too long to quit. It's got to be an error with my URL's, I just don't know what though. So, have a laugh at my expense (seriously, you should have heard Linode support when I logged into the wrong account and deleted the wrong server.. they have excellent support!) and help me amuse myself a bit through this pandemic, because I'm mostly playing with stufff as part of a bigger project I started a while before I quit computer science and went into welding..
Basically, add a page to a category. Better looking URL's with slugs, no problem, until I try to access outside of /admin with the slug. I've basically got it text for text, and am getting this:
Using the URLconf defined in first_project.urls, Django tried these URL patterns, in this order:
404
[name='index']
rango/
admin/
category/slug:category_name_slug/ [name='category']
^media/(?P.*)$
The current path, category/useless/, didn't match any of these.
I get that when I try to access localhost/rango/category/category-name-slug, or localhost/category/category-name-slug
Here is my project urls.py
from django.contrib import admin
from django.urls import path
from django.urls import include
from django.conf import settings
from django.conf.urls.static import static
from rango import views
urlpatterns = [
path('', views.index, name='index'),
path('rango/', include('rango.urls')),
path('admin/', admin.site.urls),
path('category/slug:category_name_slug/', views.category, name='category'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And this is from my app urls.py
from django.urls import path
from rango import views
app_name='rango'
urlpatterns = [
path('', views.index, name='index'),
path('category/slug:category_name_slug/', views.category, name='category'),
]
And a snippet from my index.html file, because I can't get category.html to load anywhere without a 404, I can get the slug name to show up beside the category name, if you're wondering what on earth I'm doing.
{% if categories %}
<ul>
{% for category in categories %}
<li>;{{ category.name }} {{ category.slug }};
</li>
{% endfor %}
</ul>
{% else %}
{% endif %}
and last, my app's views.py
from django.shortcuts import render
from rango.models import Category
from rango.models import Page
def index(request):
category_list = Category.objects.order_by( '-likes' )[:50]
context_dict = { 'categories': category_list }
return render(request, 'rango/index.html', context_dict)
def category(request, category_name_slug):
context_dict = {}
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
pages = Page.objects.filter(category=category)
context_dict['pages'] = pages
context_dict['category'] = category
except Category.DoesNotExist:
return render(request, 'rango/category.html', context_dict)
I get that when I try to access localhost/rango/category/category-name-slug, or localhost/category/category-name-slug
There is a rendering problem with the Markdown file. If you inspect the raw version [GitHub], you see the real urlpatterns. This needs to use angle brackets (<…>), so:
urlpatterns = [
path('', views.index, name='index'),
path('rango/', include('rango.urls')),
path('admin/', admin.site.urls),
path('category/<slug:category_name_slug>/', views.category, name='category'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#SanZo- Why are you adding the following urlpattern at two places.
path('category/slug:category_name_slug/', views.category, name='category'),
It should only be inside your app (rango).
I don't understand why you would try this.rango/ admin/ category/slug:category_name_slug/
The simplest thing to do is - if you want to access the category_slug view
then do this 127.0.0.1:8000/rango/category/{slug}/
e.g 127.0.0.1/rango/category/pillow/
I'm learning Chapter 18 18.4.2 in Python Crash Course,when i open http://localhost:8000/topics ,I'm using Django 3.0 and python 3.8
shows
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/topics
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
The current path, topics, didn't match any of these.
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.
and this is my code
learning_log\urls.py
from django.contrib import admin
from django.urls import path
from learning_logs import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index,name = 'index')
]
learning_logs\urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index,name = 'index'),
url(r'^topics/$',views.topics,name='topics')
]
views.py
from django.shortcuts import render
from .models import Topic
# Create your views here.
def index(request):
return render(request,'learning_logs/index.html')
def topics(request):
topics = Topic.objects.order_by('date_added')
context = {'topics':topics}
return render(request,'learning_logs/topics.html',context)
base.html
<p>
Learning Log-
Topics
</p>
{% block content %}{% endblock content %}
topics.html
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topics</p>
<ul>
{% for topic in topics %}
<li>{{ topic }}</li>
{% empty %}
<li>No topics have been added yet.</li>
{% endfor %}
</ul>
{% endblock content %}
and runserver shows:
Not Found: /topics
[06/Jan/2020 17:53:15] "GET /topics HTTP/1.1" 404 2077
enter image description here
First of all, good question. Love the detail.
The error is the following
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order
This means that the url /topics cannot be found. You need to import that url from the app specific urls.py into the main urls.py. This is usually done by something along the lines of
# in main urls.py
from learning_logs.urls import urlpatterns as ll_urlpatterns
# other patterns ...
urlpatterns += ll_urlpatterns
Use below code replace 'app' with your appname.
from django.contrib import admin
from django.urls import path
from learning_logs import views
from django.conf.urls import url, include
urlpatterns = [
path('admin/', admin.site.urls),
url(r'', include(('app.urls', 'app'), namespace='app')),
]
After checking several similar threads I still fail to get it work. I want to pass a simple variable from my views.py to my index.html template. But the template displays the variable 'liga1' as it is in the frontend and the variable's value isn't passed.
These are my files:
views.py
import requests
from django.shortcuts import render
import json
# Render different pages
def render_landing_page(request, template="index.html"):
liga = ['1. Bundesliga', 'Premier League', 'La liga']
return render(request, template, {'liga': liga})
index.html (only a snippet):
<!-- Sidebar -->
<div id="sidebar">
<header>
Dasocc
</header>
<ul class="nav">
<li class="countries"><img src="{% static "images/germany.png" %}" alt="germany">{{ liga }}
urls.py // project dir
from dasocc_app import views
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^$', views.render_landing_page, name='landing_page'),
url(r'^$', views.liga, name='liga'),
url(r'^dasocc-app/', include('dasocc_app.urls')),
url(r'admin/', admin.site.urls),
]
urls.py // app dir
from django.conf.urls import url
from dasocc_app import views
urlpatterns = [
#Where home is some random view from your dassocc-app
url(r'^$', views.liga, name='liga')
]
No html output at the frontend for {{ liga }} variable in index.html template:
Related project structure:
For some reason you have added your templates to your urls.py. Even though you haven't told us what URL you are going to, it is clear from the output that you are visiting the template address directly and not going to the URL that is served by the liga view.
Remove the templates from your URLs and add a URL which points to liga.
I am fairly new to Django and I am totally stuck on what is causing this error. I have done lots of searching but to no avail! Any help would be super appreciated.
The actual form works fine but when I try and submit the input data I get the error:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^admin/
^$ [name='home']
^patientlist [name='patient_list']
^patientdetail/(?P<pk>\d+)/$ [name='patient_detail']
^add_patient/$ [name='add_patient']
The current URL, spirit3/add_patient/, didn't match any of these.
My urls.py in the mysite directory looks like:
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('spirit3.urls')),
]
My urls.py in the app looks like:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^patientlist', views.patient_list, name='patient_list'),
url(r'^patientdetail/(?P<pk>\d+)/$', views.patient_detail, name='patient_detail'),
url(r'^add_patient/$', views.add_patient, name='add_patient'),
]
The relevant part of views.py:
def add_patient(request):
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save(commit=True)
return redirect('home')
else:
print form.errors
else:
form = PatientForm()
return render(request, 'spirit3/add_patient.html', {'form':form})
And the html looks like:
{% extends 'spirit3/base.html' %}
{% block content %}
<body>
<h1> Add a Patient </h>
<form action="/spirit3/add_patient/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create Patient" />
</form>
</body>
{% endblock %}
Thanks in advance! :)
the form "action" attribute is wrong... seeing your urls configuration you dont have a /spirit3/add_patient/ url, I think It is /add_patient/
or you could just use a form tag without an "action" it will post to the current page:
<form role="form" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create Patient" />
</form>
Hope this helps
As pleasedontbelong mentionned, there's indeed no url matching "/spirit3/add_patient/" in your current url config. What you have in tour root urlconf is:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('spirit3.urls')),
]
This means that urls with path starting with "/admin/" are routed to admin.site.urls, and all other are routed to spirit3.urls. Note that this does NOT in any way prefixes urls defined in spirit3.urls with '/spirit3/', so in your case, all of these urls:
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^patientlist', views.patient_list, name='patient_list'),
url(r'^patientdetail/(?P<pk>\d+)/$', views.patient_detail, name='patient_detail'),
url(r'^add_patient/$', views.add_patient, name='add_patient'),
]
will be served directly under the root path "/" - ie, the add_patient view is served by "/add_patient/", not by "/spirit3/add_patient/".
If you want your spirit3 app's urls to be routed under "/spirit3/*", you have to specify this prefix in your root urlconf, ie:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^spirit3/', include('spirit3.urls')),
]
Note that you can use any prefix, it's totally unrelated to your app name.
As a last note: never hardcode urls anywhere, django knows how to reverse an url from it's name (and args / kwargs if any). In a template you do this with the {% url %} templatetag, in code you use django.core.urlresolvers.reverse().
this NoReverseMatch error is driving me nuts. I'm using Django 1.6 and I have checked through my urls and it just doesn't work. Please kindly guide me on this.
I basically want to do something deadly simple, just when I submit a html form, I get the data I want and then redirect to a result page, but it just doesn't work...
Here is my index.html file
<form name="input" action="{% url 'whatspring:sending' %}" method="post">
{% csrf_token %}
Recipient: <input type="text" name="usrname">
<br>
<input type="submit">
</form>
<br>
my view.py
def index(request):
return render(request,'springsend/index.html')
def sending(request):
var = request.POST['usrname']
doSomethinghere()
return HttpResponseRedirect(reverse('whatspring:results'))
def results(request):
return render(request,'springsend/send_results.html')
then my app urls.py
from django.conf.urls import patterns, url
from springsend import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^results/$', views.results, name='results'),
)
and the main urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^send/', include('springsend.urls', namespace="whatspring")),
)
I have tried to look into the problem and it seems that the reverse function cannot get the name for the reverse url that I want (i.e. 'results' under the namespace 'whatspring'....)Am I missing something something trival? Please kindly help.
Your urls.py (springsend one) doesn't seem to have a url for the sending view, that's probably why {% url 'whatspring:sending' %} can't find it.
Simply change it to
from django.conf.urls import patterns, url
from springsend import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^results/$', views.results, name='results'),
url(r'^sending/$', views.sending, name='sending'), # this line
)
Every accessible view needs a url. The user's browser needs to have some address to send things. If it would just send it to your domain without url, Django would have no way to tell which url is requested. Django does not auto-generate these urls (which is probably good).
(The user himself does not need to know this url; you don't need to place any ` links anywhere.)