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')
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' %}">
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})
I'm getting this error when trying to click on the "New Color Set" button:
NoReverseMatch at /colorsets/new/
Reverse for 'user_logout' not found. 'user_logout' is not a valid view function or pattern name.
I've looked extensively through StackOverflow and elsewhere on other sites and can't seem to find what the issue is. As far a I can tell all my code is right but clearly there is an issue.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Colors</title>
<meta name"viewport" content="width=device-width, initial-scale=1">
<meta charset="uft-8">
<link rel="shortcut icon" href="/images/favicon.ico">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<nav>
<div class="container">
<a class="btn" href="{% url 'index' %}">Home</a>
{% if user.is_authenticated %}
<a class="btn" href="{% url 'colorsets:new_color' %}">New Color Set</a>
<a class="btn" href="{% url 'accounts:user_logout' %}">Logout</a>
{% else %}
<a class="btn" href="{% url 'accounts:user_login' %}">Login</a>
<a class="btn" href="{% url 'accounts:register' %}">Register</a>
{% endif %}
</div>
</nav>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
Views.py
from django.shortcuts import render
from accounts.forms import UserForm
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Account now active")
else:
print("Login Unsuccessful")
return HttpResponse("Your username and/or password are not correct")
else:
return render(request,'accounts/login.html',{})
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'accounts/register.html',{'user_form':user_form,'registered':registered})
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
accounts app urls.py
from django.conf.urls import url
from accounts import views
app_name = 'accounts'
urlpatterns = [
url(r'^register/$',views.register,name='register'),
url(r'^login/$',views.user_login,name='user_login'),
url(r'^logout/',views.user_logout,name='user_logout'),
]
project urls.py
"""colors URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from accounts import views
from colorsets import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.index,name='index'),
url(r'^accounts/',include('accounts.urls',namespace='accounts')),
url(r'^colorsets/',include('colorsets.urls',namespace='colorsets')),
]
Let me know if you need to see anything else.
The problem is in the template under the url named new_color in your colorsets namespace. You definitely used it as {% url 'user_logout' %}, while you should use it like {% url 'accounts:user_logout' %}. Just add the namespace.
Check these two things in your project:
-In settings file you should have these two codes
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
-Must have a path in project's urls.py file (as shown below)
path('users/', include('django.contrib.auth.urls')),
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 a newbie to Django and created a sample project with an app:
views.py
from django.http import HttpResponse,Http404
from django.contrib.auth.models import User
from django.template import Context
from django.template.loader import get_template
def main_page(request):
template = get_template('main_page.html')
variables = Context({
'head_title': u'Django Bookmarks',
'page_title': u'Welcome to Django Bookmarks',
'page_body': u'Where you can store and share bookmarks!'
})
output = template.render(variables)
print 'output',output
return HttpResponse(output)
urls.py
from django.conf.urls.defaults import patterns, include, url
from bookmarks.views import *
urlpatterns = patterns('',
(r'^$',main_page),
(r'^user/(\w+)/$',user_page),
#(r'login/$','django.contrib.auth.views.login')
)
main_page.html
<html>
<head>
<title>{{head_title}}</h1>
</head>
<body>
<h1>{{page_title}}</h1>
<p>{{page_body}}</p>
</body>
</html>
When I print the output variable, I see everything perfectly all right but when I run the server and point to the page, I see a blank page.
You are missing the closing tag </title>
Your template should look like this
<html>
<head>
<title>{{head_title}}</title>
</head>
<body>
<h1>{{page_title}}</h1>
<p>{{page_body}}</p>
</body>
</html>