Django How to make form fit HTML input field - python

I have a small question.
Here is my "Register page":
[![Register page][1]][1]
But when I add my form to the login, for example, I get this:
[![Page with login][2]][2]
I want to know how can I make that form box fit that HTML input field?
I don't know if I have to resize it in the forms.py or if there was a way for it to always bind up the input size that is in the HTML file.
This is the HTML:
{% load static %}
<!DOCTYPE html>
{% csrf_token %}
<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.0" />
<title>IPV QS Tool Registration</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="registration.css" />
<link rel="stylesheet" type="text/css" href="{% static 'css/style_register.css' %}" />
</head>
<body>
<form method="POST" action="">
<label>
<p class="label-txt">ENTER YOUR AMAZON EMAIL</p>
<input type="email" class="input" required />
<div class="line-box"></div>
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">ENTER YOUR AMAZON LOGIN</p>
{{form.username}}
<div class="line-box">
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">CREATE A PASSWORD</p>
<input
type="password"
class="input password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters"
required
/>
<div class="line-box">
<div class="line"></div>
</div>
</label>
<button type="submit">Submit</button>
</form>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"
></script>
<script src="registration.js"></script>
</body>
</html>
Forms.py:
class createUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']

It seems like you are missing class="input" from your input field. Please try this,
username = forms.CharField(max_length=100,
widget= forms.TextInput
(attrs={'class':'input'}))
widget= forms.TextInput(attrs={'class':'input'})
It will result in addition of this class to your CharField.
I hope this helps. Feel free to connect in case if the issue still persists.
Thanks.

Related

How to create a "simple" commentary section linked on a certain "ID"

I have a simple flask application that looks like that : MyFlaskAPP
the problem is i don't know if it's possible or not to add an "infinite amount" of comments and show them in the page of the software associated
for infos my list.html will be the interface for "admins" and list_user.html is the "user interface" because i don't want users to delete or modify thoses datas.
if somone could help me of give me somes tips btw here is my code :
app.py
from flask import Flask, render_template, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
import time
# create the extension
db = SQLAlchemy()
# create the app
app = Flask(__name__)
# configure the SQLite database, relative to the app instance folder
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///web_solinest.db"
# initialize the app with the extension
db.init_app(app)
class Webapp(db.Model):
id = db.Column(db.Integer, primary_key=True)
nom = db.Column(db.String)
pastille = db.Column(db.String)
description = db.Column(db.String)
update_time = db.Column(
db.String, default=time.strftime("%m-%d-%Y %H:%M"))
with app.app_context():
db.create_all()
#app.route("/solistatus")
def show_all():
webapps = db.session.execute(
db.select(Webapp).order_by(Webapp.nom)).scalars()
return render_template("webapp/list_user.html", webapps=webapps)
#app.route("/admin")
def webapp_list():
webapps = db.session.execute(
db.select(Webapp).order_by(Webapp.nom)).scalars()
return render_template("webapp/list.html", webapps=webapps)
#app.route("/solistatus/create", methods=["GET", "POST"])
def webapp_create():
if request.method == "POST":
webapps = Webapp(
nom=request.form["nom"],
pastille=request.form["pastille"],
description=request.form["description"]
)
db.session.add(webapps)
db.session.commit()
return render_template("webapp/create.html")
#app.route("/solistatus/update/<int:id>", methods=["GET", "POST"])
def webapp_update(id):
webapp = Webapp.query.get(id)
if request.method == "POST":
webapp.nom = request.form["nom"]
webapp.pastille = request.form["pastille"]
webapp.description = request.form["description"]
webapp.update_time = time.strftime("%m-%d-%Y %H:%M")
db.session.commit()
return render_template("webapp/update.html", webapp=webapp)
#app.route("/solistatus/<int:id>/delete", methods=["GET"])
def webapp_delete(id):
webapps = Webapp.query.get(id)
db.session.delete(webapps)
db.session.commit()
return redirect(url_for('webapp_list'))
list.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.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Admin page</title>
</head>
<body>
<h3>Add Software</h3>
<table class="display_table">
<thead>
<tr>
<th style="width: 10px;">Pastille</th>
<th style="width: 300px;">Nom</th>
<th>ID</th>
</tr>
</thead>
<tbody>
{% for Webapp in webapps %}
<tr>
<td class="tiny"><img style="width: 40px;"
src="https://icones.pro/wp-content/uploads/2021/04/icone-cercle-rempli-{{Webapp.pastille }}.png"
style="width: 10%;" alt=""></td>
<td>{{ Webapp.nom }}</td>
<td>{{ Webapp.id }}</td>
<td>Delete</td>
<td>Update</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
create.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.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Create page</title>
</head>
<html>
<body>
<h3>Software creation</h3>
Home page<br>
<form action="{{ request.path }}" method="post">
<label for="pastille">Pastille</label><br>
<select type="text" name="pastille" id="pastille" class="form-control">
<option value="vert">Vert</option>
<option value="rouge">Rouge</option>
</select><br>
<label for="nom">Nom</label><br>
<input type="text" name="nom" placeholder="nom" /><br>
<label for="description">Description</label><br>
<textarea name="description" placeholder="description"></textarea><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
update.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.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Create page</title>
</head>
<body>
<h1 id="homepage">Home page</h1><br>
<form method="post">
<div class="form-group">
<label for="nom">Nom</label>
<input type="text" class="form-control" id="nom" name="nom" value="{{ webapp.nom }}">
</div>
<div class="form-group">
<label for="pastille">Pastille</label>
<select type="text" name="pastille" id="pastille" class="form-control">
<option value="rouge">Rouge</option>
<option value="vert">Vert</option>
</select>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea type="text" class="form-control" id="description"
name="description">{{ webapp.description }}</textarea>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</body>
Thank you a lot if someone could help me or inform me I'm interested
i tried to create a new table called history but i don't know how to link the table 1 to the table 2 using the ID and display the comment section of the ID n°1

Getting Image from image field to views.py model

I am making a social media site in Django. I have a page for making a new post. It has a form with a file field to take an image upload. I want to get the image in views.py to save in the database. In the image variable, a string is getting saved with the name of the image. Also, I don't want to use any external form like forms.py. Here I have also tried request.FILES["image"] but it returned an empty dict.
Views.py
def newpost(request):
if request.method == "POST":
image = request.POST.get("image")
caption = request.POST.get("caption")
post = Post(Image=image,Caption=caption,Owner=request.user.username)
post.save()
return redirect("/")
return render(request,"newpost.html")
newpost.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spark X- New Post</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/newpost.css' %}">
<script class="jsbin" src="{% static 'js/jquery.js' %}"></script>
<link rel="icon" href="{% static 'images/favicon123.png'%}" type="image" sizes="16x16" class="favicon">
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</head>
<body>
<div class="header">
<span class="topband">
<img src="{% static 'images/back icon.png'%}" class="topicon">
</span>
<div class="logoholder">
<p class="logotext">New Post</p>
</div>
</div>
<div class="mainarea">
<form action="" method="post">{% csrf_token %}
<input type="file" name="image" id="image" accept="image/*" class="imageUpload" onchange="readURL(this);"/>
<label for="image"><img src="{% static 'images/camera icon.png' %}" class="cameraIcon" id="blah"></label>
<input type="text" name="caption" placeholder="Caption... " class="caption">
<button type="submit" class="submit">Post</button>
</form>
</div>
</body>
</html>
models.py
class Post(models.Model):
Id = models.AutoField(primary_key=True)
Image = models.ImageField(upload_to="Posts")
date = models.DateTimeField(auto_now=True)
Caption = models.TextField()
Your help will really be appreciated.
I have figured it out. Just used request.FILES["image"] and added enctype="multipart/form-data" in form and it worked.

How do I reset my HTML form with Python Flask?

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)

How to connect my two HTML pages using flask

I am trying to link two html pages 'home.html' and 'result.html' using flask framework but it is not working. Also the changes that I make in html page are not reflecting when page is opened with flask.
Here's the code for 'home.html' :
<!doctype <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>IRIS PREDICTOR</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="/static/main.css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<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.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
</head>
<body>
<h1 class="text-info">IRIS PREDICTION</h1>
<form action="/result" method="POST">
<div class="col-2" id="abc">
<label for="ex2">Sepal Length</label>
<input class="form-control" id="ex2" type="text" name="s_length">
</div>
<div class="col-2">
<label for="ex2">Sepal Width</label>
<input class="form-control" id="ex2" type="text" name="s_width">
</div>
<div class="col-2">
<label for="ex2">Petal Length</label>
<input class="form-control" id="ex2" type="text" name="p_length">
</div>
<div class="col-2">
<label for="ex2">Petal Width</label>
<input class="form-control" id="ex2" type="text" name="p_width">
</div>
<button class="btn btn-outline-secondary" type="button" id="button-addon1">Predict</button>
</form>
</body>
</html>
Code for 'result.html':
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PREDICTION RESULT</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="/static/style.css" />
<script src="main.js"></script>
</head>
<body>
<p>Sepal Length: {{sepal_length}}</p>
<p>Sepal Width: {{sepal_width}}</p>
<p>Petal Length: {{petal_length}}</p>
<p>Petal Width: {{petal_width}}</p>
<p>Species: {{predict_result}}</p>
</body>
</html>
And code for script.py is:
from flask import Flask,render_template,request
from sklearn.externals import joblib
app=Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/predict',methods=['POST'])
def show():
if request.method=='POST':
sepal_length=request.form['s_length']
sepal_width=request.form['s_width']
petal_length=request.form['p_length']
petal_width=request.form['p_width']
data=[[float(sepal_length),float(sepal_width),float(petal_length),float(petal_width)]]
model=joblib.load('iris_model.pkl')
predict_result=model.predict(data)
return render_template('result.html',sepal_length=sepal_length,sepal_width=sepal_width,petal_length=petal_length,petal_width=petal_width,predict_result=predict_result)
if __name__=='__main__':
app.run(debug=True)
What should i do now?
I have your code working. Your #app.route for the show function was for /result but home.html was posting the data to /result/
Also your button on home.html wasn't a submit button so it never posted the form.
Full listings of the files below
script.py - i've commented out the joblib items
from flask import Flask,render_template,request
#from sklearn.externals import joblib
app=Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/predict',methods=['POST'])
def show():
if request.method=='POST':
sepal_length=request.form['s_length']
sepal_width=request.form['s_width']
petal_length=request.form['p_length']
petal_width=request.form['p_width']
data=[[float(sepal_length),float(sepal_width),float(petal_length),float(petal_width)]]
#model=joblib.load('iris_model.pkl')
#predict_result=model.predict(data)
predict_result="TEST"
return render_template('result.html',sepal_length=sepal_length,sepal_width=sepal_width,petal_length=petal_length,petal_width=petal_width,predict_result=predict_result)
if __name__=='__main__':
app.run()
home.html
<!doctype <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>IRIS PREDICTOR</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="/static/main.css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<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.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
</head>
<body>
<h1 class="text-info">IRIS PREDICTION</h1>
<form action="/predict" method="POST">
<div class="col-2" id="abc">
<label for="ex2">Sepal Length</label>
<input class="form-control" id="ex2" type="text" name="s_length">
</div>
<div class="col-2">
<label for="ex2">Sepal Width</label>
<input class="form-control" id="ex2" type="text" name="s_width">
</div>
<div class="col-2">
<label for="ex2">Petal Length</label>
<input class="form-control" id="ex2" type="text" name="p_length">
</div>
<div class="col-2">
<label for="ex2">Petal Width</label>
<input class="form-control" id="ex2" type="text" name="p_width">
</div>
<button class="btn btn-outline-secondary" type="submit" id="button-addon1">Predict</button>
</form>
</body>
</html>
result.html is unchanged from your example
I hope the explanation below helps others in the future.
Please make sure that you save all 3 files in the same directory(folder). In the same folder you saved the script.py, create another folder and name it "templates". Place both html files in this folder. Then, run script.py in your terminal, you should see the output on the server.
Usually, the reason why changes are not reflecting in your page is because you might have forgotten to save the changes after they are made. One might think that it is automatically saved but it is not.
Put your both templates in 'templates' directory where your scripts.py located. Flask search template files in 'templates' directory.
Remove space between #app.route and def home().

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!

Categories