I've completed all of the sections of the Django tutorial and have started my own project now to practice. I am back at the beginning tutorial where it talks about views/mapping urls. I also am following this tutorial for trying to display a table
For whatever reason, I cannot figure out why when I try to hit http://127.0.0.1:8000/show/, it returns 404. I've been staring at this for the last hour and have been going back and forth between the tutorial and my code. I had to do things a little bit differently than the 2nd mentioned tutorial, mainly that they didn't talk about creating an app-level urls.py file. Everything up to this point has worked fine. The models.py file created the table within the MySQL database, as I can see it in the workbench.
My project structure is like this:
mywebsite (project)
displaydata (app)
Here is my project level urls.py file located in the mywebsite folder:
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('admin/', admin.site.urls),
path('displaydata/', include('displaydata.urls'))
]
Here is my app-level urls.py file located in the displaydata folder:
from django.urls import path
from . import views
app_name = 'displaydata'
urlpatterns = [
path('', views.show, name='show')
]
Here is my displaydata views.py file:
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import Shipment
# Create your views here.
def show(request):
shipments = Shipment.objects.all()
return HttpResponse(render(request,"show.html",{'shipment':shipments}))
Here is the show.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Django CRUD Operations</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>Shipment ID</th>
<th>Driver</th>
<th>Destination City</th>
<th>Destination State</th>
</tr>
</thead>
<tbody>
{% for ship in shipment %}
<tr>
<td>{{ship.id}}</td>
<td>{{ship.driver}}</td>
<td>{{ship.destination_city}}</td>
<td>{{ship.destination_state}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
It will hit the show view for the URL 127.0.0.1:8000/displaydata/.
This the case because you include all the displaydata urls with the displaydata/ prefix. In the url patterns of your displaydata app, there is one pattern: the empty string, so it will match this for the path /dispaydata.
If you want to access the view with /show, you can use an empty string as prefix in the project urls:
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('displaydata.urls'))
]
and then for the displaydata urls work with:
from django.urls import path
from . import views
app_name = 'displaydata'
urlpatterns = [
path('/show/', views.show, name='show')
]
If the template is located at app_name/templates/app_name/show.html, then you render the template with:
def show(request):
shipments = Shipment.objects.all()
return render(request,'app_name/show.html',{'shipment': shipments})
Related
I am new to django. I wanted to upload an image but it doesn't show up on website. Instead, it shows a broken image icon. I tried to use load static block but it still doesn't work.
My html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Website</title>
</head>
<body>
<h1>Hello</h1>
{% load static %}
<img src="{% static 'webdev/static/webdev/images/images.jpg' %}">
</body>
urls.py file:
from django.contrib import admin
from django.urls import path
from homepage import views
urlpatterns = [
path('', views.home_page, name='home'),
path('admin/', admin.site.urls),
]
views.py file:
from django.shortcuts import render
from django.http import HttpResponse
def home_page(request, *args, **kwargs):
return render(request, 'home.html', {})
file tree: https://i.stack.imgur.com/EYxNI.png
The documentation on Serving static files during development explains how to set up static files. You need to add the views that serve the static files to the urlpatterns:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from homepage import views
urlpatterns = [
path('', views.home_page, name='home'),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
This will serve static files when DEBUG is set to True. In case of production (DEBUG = False), Django does not serve static files. Then you should configure the webserver (nginx/apache/…) to serve the static and media files, or work with a CDN.
Furthermore the path is:
<img src="{% static 'webdev/images/images.jpg' %}">
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.
views.py file:
from django.http import HttpResponse
from django.template import loader
def index(request):
template = loader.get_template('upload/testpage.html')
return HttpResponse(template.render)
app/templates/app/testpage.html file:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="file" id="upload" name="upload" style="visibility: hidden; width: 1px; height: 1px" multiple />
Upload
</body>
</html>
app/urls.py file:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),]
project/urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^upload/', include('upload.urls')),]
Getting an error when running file on local server 127.0.0.1:8000/app of "TemplateDoesNotExist at /app/"
How can this be resolved?
With your current file path app/templates/app/testpage.html this one should works
def index(request):
template = loader.get_template('app/testpage.html')
return HttpResponse(template.render)
Another way to do it is to change your template path to app/templates/upload/testpage.html
I think you did not create any upload folder inside templtes folder.
If you have app folder like that
app/templates/app/testpage.html
Now, you can fix it
template = loader.get_template('app/testpage.html')
Try this,
from django.shortcuts import render
def index(request):
return render(request, 'app/testpage.html')
I have seen several related questions on this subject, but none have helped solve my problem so far.
I created a project "mysite" and an app within this project, aptly called "app". mysite.urls looks like so:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('app.urls', namespace='app')),
]
app.urls
from django.conf.urls import include, url
from app import views
urlpatterns = [
url(r'^$', views.home),
url(r'^hello/$', views.students),
]
app.views
from django.shortcuts import render
def home(request):
return render(request, "base.html")
def students(request):
return render(request, "students.html")
app.templates.base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>My site</title>
</head>
<body>
<h1>My site</h1>
<ul>
<li>
Students
</li>
<ul>
<p>Thanks for visiting my site.</p>
<!-- {% endblock %} -->
</body>
</html>
The django error message indicates that it has something to do with the line
Students
but I can't seem to figure it out. Any help would be greatly appreciated
You haven't named app's urls.
# app.urls
urlpatterns = [
url(r'^$', views.home, name="home"),
url(r'^hello/$', views.students, name="students"),
]
I'm trying to get a form action redirect to another page, however, I'm not too farmiliar with the Django framework. I went through the polls tutorial.
The current urls.py in my project is:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from WebApp import views
from StripCal import views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^webapp/', include('WebApp.urls', namespace="WebApp")),
url(r'^stripcal/', include('StripCal.urls', namespace="StripCal")),
)
The url.py in my stripcal app is:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from StripCal import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^run', views.detail, name='detail'),
)
When I type in
http://127.0.0.1:8000/stripcal/
http://127.0.0.1:8000/webapp/
It successfully goes to two different apps. However, I'm not too familiar with {% url 'app_name:view_name' %} syntax. It seems like 'app_name:view_name' becomes /app_name/view_name
This is my current view:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
# Create your views here.
def index(request):
context = {'somethingDownByCelery': "heh"}
return render(request, 'StripCal/index.html', context)
def detail(request):
context = {'somethingDownByCelery': "heh"}
return render(request, 'StripCal/detail.html', context)
My Index.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'StripCal/index.css' %}"/>
<form action="{% url 'stripcal:detail'%}" method="post">
{% csrf_token %}
<p> StripCal Input </p>
<textarea name="StripCal_Input" cols="30" rows="10"> </textarea>
<br> <br>
<input type="submit" value="Submit">
</form>
My Detail.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'StripCal/detail.css' %}"/>
Hello Detail!
When I remove action={% url 'stripcal:detail' %} the webpage loads, however, when I put it in, the page does not even load (HTTP 500).
try to change:
StripCal.url.py
urlpatterns = patterns('StripCal.views',
url(r'^$', 'index', name='index'),
url(r'^run','detail', name='detail'),
)