How do I reset my HTML form with Python Flask? - python

I'm building a very simple web app (using Python Flask) that will display some images to the user and get some response from the user.
Below is my code (ignoring the other parts of my code not related to this question):
#app.route('/gallery',methods=['GET','POST'])
def get_gallery():
image_names = os.listdir(r'C:\Users\xxxvn\images')
b=[str(i)+"|"+str(request.form.get(i)) for i in image_names]
print (b)
return render_template("gallery.html", image_names=image_names)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Gallery</h1>
</div>
{{image_names}}
<hr>
<form method="POST">
{% for image_name in image_names %}
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<img class="img-responsive" src=" {{url_for('send_image', filename=image_name)}}">
<input type="radio" name={{image_name}} id="radio1" value="YES" />YES<br>
<input type="radio" name={{image_name}} id="radio2" value="NO"/>NO<br>
<hr>
</div>
{% endfor %}
<input type="submit" name="submit_button" value="SUBMIT"/>
</form>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous"></script>
</body>
</html>
My current app
Question:
I want to reset the form as soon as the user hits submit and capture the output in list "B". The form should not be resubmitted with old values if the user hits refresh.

Do a request method check and put in your capture login in it.
from flask import request
#app.route('/gallery',methods=['GET','POST'])
def get_gallery():
image_names = os.listdir(r'C:\Users\xxxvn\images')
if request.method == "POST":
b=[str(i)+"|"+str(request.form.get(i)) for i in image_names]
print (b)
return render_template("gallery.html", image_names=image_names)

Related

Flask Form fields not refreshing and flash messages not working

I've looked everywhere and the examples aren't working for me code below:
I'm facing 2 problems with my code I'd be happy with a simple fix for each and go into an the advanced problem I'mm trying to solve
Problem 1: When I submit the form when the page refreshes the form fields still contain the information and are not blank. (Advanced problem) I'd like it to lock the fields and show a success message under the form like the original bootstrap form functioned this is a startbootstrap template i'm using the free portfolio I believe for the framework
Problem 2: I can not retrieve the successful flashed message I can only display the flashed message if an error occurs and the messages only display when I go to validate the form the success message DOES NOT display no matter what even after the form validates, (advanced) I'd like error messages to appear when the focus leaves the field like the original startbootstrap form
main.py
from flask import Flask, render_template, redirect, url_for, flash, request, abort
from flask_bootstrap import Bootstrap
from forms import ContactForm
from datetime import date
app = Flask(__name__)
app.config['SECRET_KEY'] = 'SomethingSecret'
Bootstrap(app)
current_year = date.today().year
#app.route('/', methods=['GET', 'POST'])
def home_page():
form = ContactForm()
if request.method == 'POST' and form.validate_on_submit():
flash(u'Successfully sent your message')
return redirect(url_for('home_page', form=form))
return render_template('index.html', year=current_year, form=form)
if __name__ == "__main__":
app.run(debug=True)
Here is my layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Online Portfolio</title>
<!-- Favicon-->
<link rel="icon" type="image/x-icon" href="{{url_for('static', filename='assets/favicon.ico')}}" />
<!-- Font Awesome icons (free version)-->
<script src="https://use.fontawesome.com/releases/v5.15.4/js/all.js" crossorigin="anonymous"></script>
<!-- Google fonts-->
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css" />
<!-- Core theme CSS (includes Bootstrap)-->
<link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet">
</head>
<body id="page-top">
<!-- Navigation-->
<nav class="navbar navbar-expand-lg bg-secondary text-uppercase fixed-top" id="mainNav">
<div class="container">
<a class="navbar-brand" href="#page-top">I Will Develop Your Dreams Online</a>
<button class="navbar-toggler text-uppercase font-weight-bold bg-primary text-white rounded" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
Menu
<i class="fas fa-bars"></i>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ms-auto">
<li class="nav-item mx-0 mx-lg-1"><a class="nav-link py-3 px-0 px-lg-3 rounded" href="#portfolio">Portfolio</a></li>
<li class="nav-item mx-0 mx-lg-1"><a class="nav-link py-3 px-0 px-lg-3 rounded" href="#about">About</a></li>
<li class="nav-item mx-0 mx-lg-1"><a class="nav-link py-3 px-0 px-lg-3 rounded" href="#contact">Contact</a></li>
</ul>
</div>
</div>
</nav>
{% with messages=get_flashed_messages() %}
{% for category, message in messages %}
<div class='alert text-center alert-dismissible fade show m-auto'>
{{ message }}
</div>
{% endfor %}
{% endwith %}
{% block body %}{% endblock %}
index.html
{% block body %}
<form id="contactForm" method="POST" data-sb-form-api-token="API_TOKEN">
<!-- Name input-->
<div class="form-floating mb-3">
{{ form.name(class_='form-control test', type='text', placeholder='Enter your name...') }}
{% with messages = get_flashed_messages() %}
{% if messages %}
<div>
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
{% endif %}
{% endwith %}
<label for="name">Full name</label>
</div>
{% endblock %}

I don't understand the reason for this error "jinja2.exceptions.TemplateRuntimeError: extended multiple times"

My layout.html file is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" //Since this is the base template, this will be rendered. This can stay the same for all the html pages
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><!--creating blocks. Blocks allows our template to change some specific functionality of the base template-->
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.37.1" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-uWxY/CJNBR+1zjPWmfnSnVxwRheevXITnMqoEIeG1LJrdI0GlVs/9cVSyPYXdcSF" crossorigin="anonymous">
{% block head %}
<title>AM Calibration</title>
{% endblock %}
</head>
<body> <!--By creating the block, the content below is going to be shown in every page-->
{% include 'includes/_navbar.html' %}
<div class="container">
{% block body %}
{% endblock %}
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.min.js">
</body>
</html>
I have extended the layout.html file in several different templates and not errors but when I {% entends "layout.html"%} in the register.html file, I get the "jinja2.exceptions.TemplateRuntimeError: extended multiple times"
I have used WTForms to create the registration form.
class RegisterForm(Form):
name = StringField('Name', [validators.Length(min=1, max=50)])
username = StringField('Username', [validators.Length(min=4, max=25)])
email = StringField('Email', [validators.Length(min=6, max=50)])
password = PasswordField('Password', [
validators.DataRequired(),
validators.EqualTo('confirm', message='Passwords do not match')
])
confirm = PasswordField('Confirm Password')
Routing the registration form to the Home page
#app.route("/register", methods=['GET','POST'])
def register():
form = RegisterForm(request.form) #the request function help to bring in the form.
if request.method == 'POST' and form.validate():
return render_template("register.html")
return render_template("register.html", form=form)
if __name__== "__main__":
##debug=True is a keyword argument that will allows not to rerun the server everytime we make a change. and automatically update the website.
app.run(debug=True)
My register.html file is in the templates folder. This is the Registration form and the _formhelper.html is used here to improve the appearence of the form. It looks like below:
{% extends "layout.html" %}
{% block body %}
<h1>Register</h1>
{% from "includes/_formhelpers.html" import render_field %}
<form method="POST" action="">
<div class="form-group">
{{render_field(form.name, class_="form-control")}}
</div>
<div class="form-group">
{{render_field(form.email, class_="form-control")}}
</div>
<div class="form-group">
{{render_field(form.username, class_="form-control")}}
</div>
<div class="form-group">
{{render_field(form.password, class_="form-control")}}
</div>
<div class="form-group">
{{render_field(form.confirm, class_="form-control")}}
</div>
<p><input type="submit" class="btn btn-primary" value="Submit"></p>
</form>
{% endblock %}

MultiValueDictKeyError: 'content'

i'm going to make the todo list using django...i did some code...but it throws an multiplevaluekeyerror
i tried c = request.POST.get('content', False)
but it gives always as False value
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import TodoItem
# Create your views here.
def home(request):
return render(request, 'home.html')
def work(request):
all_todo_items = TodoItem.objects.all()
return render(request, 'work.html', {'all_items': all_todo_items})
def addTodo(request):
c = request.POST['content']
new_item = TodoItem(content = c)
new_item.save()
return HttpResponseRedirect('/work/')
def deleteTodo(request, todo_id):
item_to_delete = TodoItem.objects.get(id=todo_id)
item_to_delete.delete()
return HttpResponseRedirect('/work/')
work.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'css/work.css' %}">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
<link rel="icon" href="{% static 'images/list.png' %}" type="image/png">
<title>Tasks</title>
</head>
<body>
<div class="container justify-content-center wrap1">
<div class="text-center heading">
<p><u>write your everyday task here!!!<u></p>
</div>
</div>
<ul style="list-style: none; color: #1b0573; font-weight: bold;" class="text-center">
{% for todo_item in all_items %}
<li>
<div class="row">
<div class="col-sm-6">
{{ todo_item.content }}
</div>
<div class="col-sm-2">
{{ todo_item.date_created }}
</div>
<div class="col-sm-1">
<form action="/deleteTodo/{{ todo_item.id }}" method="post" style="display: inline;">
{% csrf_token %}
<div class="form-group">
<button class="btn btn-outline-danger"><i class="fas fa-trash"></i></button>
</div>
</form>
</div>
</li>
{% endfor %}
</ul>
<div class="container">
<div class="row">
<div class="col-sm-11">
<form action="/addTodo/" method="post">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" placeholder="write your task" name="content">
</div>
</form>
</div>
<div class="col-sm-1">
<form action="/addTodo/" method="post">
{% csrf_token %}
<div class="form-group">
<button class="btn btn-outline-success"><i class="fas fa-plus"></i></button>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('work/', views.work, name = 'work'),
path('addTodo/', views.addTodo, name = 'work'),
path('deleteTodo/<int:todo_id>/', views.deleteTodo, name = 'work'),
]
i was expecting no errors...but it throws an multiplevaluekeyerror
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'content'
you need submit first <form> that you have in your code that include <input name="content"> so in view can using request.POST["conten"] to get value of` . try this:
<div class="container">
<div class="row">
<div class="col-sm-11">
<form action="/addTodo/" method="post">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" placeholder="write your task" name="content">
<input type="submit" value="submit new task">
</div>
</form>
</div>
</div>
</div>

Django Upload Image can not find uploaded image

I am new to Django and deploying upload image function recently.
I developed simple HTML template and it worked, but somehow, I could not find the uploaded images.
Below are my code.
settings.py (relevant lines)
MEDIA_ROOT = '/Users/jenny/Envs/django_test/static/'
MEDIA_URL = '/media/'
models.py
from django.db import models
from time import time
def get_upload_file_name(instance, filename):
return "uploaded_files/%s_%s" % (str(time()).replace('.','_'), filename)
# Create your models here.
class UploadImage(models.Model):
thumbnail = models.FileField(upload_to=get_upload_file_name)
def __unicode__(self):
return self.thumbnail
forms.py
from django import forms
from .models import UploadImage
class UploadImageForm(forms.ModelForm):
class Meta:
model = UploadImage
fields = ('thumbnail',)
views.py
def uploadtest(request):
return render_to_response("uploadtest.html",context_instance=RequestContext(request))
def uploadtest1(request):
if request.POST:
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/uploadtest1/',context_instance=RequestContext(request))
else:
form = UploadImageForm()
return render_to_response ('uploadtest1.html',context_instance=RequestContext(request))
uploadtest.html
<form action="{% url "uploadtest1" %}" method="post" enctype="multipart/form-data">{% csrf_token %}
<p>
<input id="id_image" type="file" class="" name="image">
</p>
<input type="submit" value="Submit" />
</form>
uploadtest1.html
<p> uploaded! </p>
Would you please help me point out the problem? And how do I change the code to make it work?
I think you have misspelled your html input. In your model the field is named thumbnail, but the name of your input is image.
Make your input read like:
<input id="id_thumbnail" type="file" class="" name="thumbnail">
I solved the problem and now the code is running well on my launched website.
forms.py
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
models.py
from django.db import models
# Create your models here.
class Document(models.Model):
#docfile = models.FileField(upload_to='documents/%Y/%m/%d')
docfile = models.FileField(upload_to='documents/')
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from uploadfile.models import Document
from uploadfile.forms import DocumentForm
def imageupload(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('uploadfile.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
doc_list = []
documents = Document.objects.all()
for document in documents:
doc_list.append(document.docfile.name)
print doc_list[-1]
# Render list page with the documents and the form
return render_to_response('imageupload.html',
{'documents': documents,'form': form},
context_instance=RequestContext(request))
def imageuploadresult(request):
#here I used PyImgur package to upload image and get public url. Use sbi to get the Google BestGuess. What I return to this page is the uploaded image and google best guess. I will skip this part of code.
return render_to_response(
'imageuploadresult.html',
{'query': q, 'imagepath':path2},
context_instance=RequestContext(request))
imageupload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title> Image Upload of **** System</title>
<!-- Bootstrap core CSS -->
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="/static/css/dashboard.css" rel="stylesheet">
<!-- Custome CSS -->
<link href="/static/css/dataurl2.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="/static/js/ie8-responsive-file-warning.js"> </script><![endif]-->
<script src="/static/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<!--script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script-->
<!--script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"> </script-->
<script src="/static/js/html5shiv.min.js"></script>
<script src="/static/js/respond.min.js"></script>
<!--script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
})
</script-->
<![endif]-->
</head>
<body>
<!--div class="loader"></div-->
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data- toggle="collapse" data-target="#navbar" aria-expanded="false" aria- controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href='/navigation/'>AKEOS</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li>Dashboard</li>
<li>Settings</li>
<li>Profile</li>
<li>Help</li>
</ul>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li>Reports</li>
<li>Export</li-->
</ul>
<ul class="nav nav-sidebar">
<li class="active">(current)</span></li>
<li>Analytics</li>
<li>Export</li-->
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main list-group">
<h1></h1>
<h2></h2>
<h3 class="custome-bar">
<h1></h1>
<h2></h2>
<form action="{% url "imageuploadresult" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" style="font- size:10pt;color:white;background-color:#339933;border:2px solid #339933;padding:3px" /></p>
</form>
</h3>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/docs.min.js"></script>
<script src="/static/js/pace.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/static/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
imageuploadresult.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title> Image Upload of **** System</title>
<!-- Bootstrap core CSS -->
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="/static/css/dashboard.css" rel="stylesheet">
<!-- Custome CSS -->
<link href="/static/css/dataurl2.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="/static/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="/static/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<!--script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script-->
<!--script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script-->
<script src="/static/js/html5shiv.min.js"></script>
<script src="/static/js/respond.min.js"></script>
<!--script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
})
</script-->
<![endif]-->
</head>
<body>
<!--div class="loader"></div-->
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href='/navigation/'>AKEOS</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<!--li>You searched for:<strong> {{query}} </strong></li-->
<li>Dashboard</li>
<li>Settings</li>
<li>Profile</li>
<li>Help</li>
</ul>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
</ul>
<ul class="nav nav-sidebar">
<!--li>Analytics</li>
<li>Reports</li>
<li>Export</li-->
</ul>
<ul class="nav nav-sidebar">
<li class="active">(current)</span></li>
<!--li>Reports</li>
<li>Analytics</li>
<li>Export</li-->
</ul>
</div>
<!--div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"-->
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main list-group">
<h3 class="custome-bar">
<h3>The Best Guess is:<strong> {{query}} </strong>
<form action="/main-page/" method="get">
<h5> To start over again, click the sidebars; to continue, click the button "Search" </h5>
<h5>
<input type="submit" name = "Submit" value="Search" >
</h5>
<h3></h3>
</form>
</h3>
<!--a class="btn btn-large btn-info" href="/main-page/">Search</a-->
<p><img src={{imagepath}} class='img-responsive' /></p>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/docs.min.js"></script>
<script src="/static/js/pace.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/static/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
create table in MySQL
table name : upload file_document
table columns : ID, docfile
Now you can get it work on your website!
Have a nice day!

Django template {% include not working

I'm new to Django. I'm having problem including a sub-template in a main template. The directory structure of my project is attached in the snapshot. I removed the default views.py and created my own folder named "views" and put my views in it. Here is what I've done:
1. app/views/__init__.py
from .home import *
2. app/views/home.py
from django.shortcuts import render
def index(request):
return render(request, 'home.html')
3. app/templates/home.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
Administrator Section
</title>
<link type="text/css" rel="stylesheet" href="{% static "css/common.css" %}"/>
<link type="text/css" rel="stylesheet" href="{% static "css/theme/transdmin.css" %}"/>
<link type="text/css" rel="stylesheet" href="{% static "css/login.css" %}"/>
<script type="text/javascript" src="{% static "js/jquery-1.10.2.js" %}"></script>
<script type="text/javascript" src="{% static "js/common.js" %}"></script>
<script type="text/javascript" src="{% static "js/login.js" %}"></script>
</head>
<body>
<div>
<div id="wrapper" class="ys-adminform">
{% include "includes.header_logo.html" %}
<form id="form-login" class="admin-section-form frm">
<div class="header">
<br/>
<h1>Login</h1>
<br/>
</div>
<div class="content">
<div class="form-row">
<input name="email" class="input" placeholder="Email" type="text"/>
<div class="user-icon"></div>
</div>
<div class="form-row">
<input name="password" class="input password" placeholder="Password" type="password"/>
<div class="pass-icon"></div>
</div>
</div>
<div class="footerlogin">
<input class="button" name="btn-login" value="Authenticate" type="button"/>
<div class="message" style="font-weight: bold; padding-top:16px;"> </div>
</div>
</form>
</div>
</div>
{% include "includes.footer.html" %}
</body>
</html>
The problem is include is not adding content from the sub-views.
I understand it could be a path problem but I tried various options like:
{% include "includes.header_logo.html" %}
{% include includes.header_logo.html %}
{% include "includes/header_logo.html" %}
{% include "templates.includes.header_logo.html" %}
{% include "app.templates.includes.header_logo.html" %}
etc.
You have to use directory slashes (/), not dots (.)
For example:
{% include "includes.footer.html" %}
becomes this:
{% include "includes/footer.html" %}
As suggested by Leistungsabfall, "includes/footer.html" works. The header was not working because it had:
This line must be crashing and because of which header was not working.
Simply add template folder with slash .... like
{% include "blog/footer.html" %}

Categories