Flask wtforms not allowing image upload - python

Dears,
I have been struggling with uploading an image on a flask form in my application. I have simplified the code to just show if the form has picked up a file by a print statement. The script is as follows:
from flask import Flask, render_template, session, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import SubmitField
from flask_wtf.file import FileField
from PIL import Image
import os
from main import app
class Uploadform(FlaskForm):
picture = FileField('Update Profile Pic')
submit = SubmitField('Submit')
#### route
#app.route('/', methods=['GET', 'POST'])
def upload():
form = Uploadform()
path = app.root_path
if form.validate_on_submit:
print('form submitted')
if form.picture.data:
print('image available')
img = form.picture.data
print(img)
else:
print('no image')
return render_template ('form.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
HTML form goes a follows:
<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>Document</title>
</head>
<body>
<form method="POST" action="{{url_for('upload')}}">
{{ form.hidden_tag() }}
{{ form.csrf_token }}
{{form.picture.label}} <br>
{{form.picture}} <br>
{{form.submit() }} <br>
</form>
</body>
</html>
When I run the above I get the print statements:
'form submitted' and
'no image'
Many thanks for your help in advance.

<form method="POST" action="{{url_for('upload')}}" enctype="multipart/form-data">
multipart/form-data this value is necessary if the user will upload a file through the form.

if form.validate_on_submit:
needs to be
if form.validate_on_submit():

Related

How to automatically refresh chat app to be in real-time

I have this very basic chat app, where everyone can chat in one huge group. And when I send messages, other people have to refresh their web page to see new messages. I am just wondering if anyone has any idea how to do this. By the way, the app is made with python Flask and HTML.
from flask import Flask, render_template, request, url_for, redirect
import database as db
app = Flask(__name__)
app.secret_key = 'ItDoesntMatter'
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('/index.html', messages=db.get_messages())
#Else
message = request.form['message']
db.send_message(message)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run()
<!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">
<title>Chat</title>
</head>
<body>
{% for message in messages %}
<div>At {{ message[1] }}: <strong>{{ message[0] }}</strong></div>
{% endfor %}
<form method="POST" action="/">
<input type="text" placeholder="message" name="message">
<button type="submit" id="btn">Send</button>
</form>
</body>
</html>
I tried to do this with a turbo-flask, but it didn't work. I was also on google for like 1 hour and I didn't find anything.

Allowing users to edit or delete list of uploaded files on Flask before submitting

Currently building a Flask app and using wtforms to help with building a file upload field, but I would like users to have the option to view the (multiple) file names they have already uploaded, either add more files, or remove some files that might have been wrongly uploaded, before finally clicking submit and the final list of files are then processed. Would prefer to continue using wtforms but open to any other solutions.
Minimum example: App.py
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, MultipleFileField, SubmitField
app = Flask(__name__)
app.config['SECRET_KEY'] = 'example'
class exampleUpload(FlaskForm):
name = StringField('name')
input_files = MultipleFileField('files')
submit = SubmitField('submit')
#app.route('/')
def index():
form = exampleUpload()
if form.validate_on_submit():
# allow user to freely add, remove, make sure that uploaded files are correct before
# pressing the submit button
if form.submit.data:
files = form.input_files.data
# do_something(files)
return '<h1> Done'
return render_template('index.html', form=form)
if __name__ == "__main__":
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ form.name }}
{{ form.input_files }}
<hr>
{{ form.submit }}
</body>
</html>

not able to upload and display django form

1.views.py
from django.shortcuts import render
from . models import User
from .forms import Userform
def Home(request):
if request.method == "POST":
form = Userform(request.POST or None,request.FILES or None)
if form.is_valid():
form.save()
else:
form = Userform()
return render(request,"home.html",{"form":form})
def read(request):
read = User.objects.all()
return render(request,"read.html",{"read":read})
2.models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=12)
rollno = models.IntegerField()
# files = models.FileField()
3.form.py
from django import forms
from .models import User
class Userform(forms.ModelForm):
class Meta:
model = User
fields = ('name','rollno')
urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("",views.Home,name="Home"),
path("read/",views.read, name="read"),
]
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
4.home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="POST" action="read/" enctype="multipart/form-data">
{%csrf_token%}
{{form}}
<button type=submit>click to submit</button>
</form>
</body>
</html>
read.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{%block containt%}
{%for i in read%}
{{i.name}}
{{i.rollno}}
{%endfor%}
{%endblock%}
</body>
</html>
i want to add data to django admin using a form but data is not uploading at django admin
Not able to upload data into django admin hence cant read it
please help
i want to add data to django admin using a form but data is not uploading at django admin
Not able to upload data into django admin hence cant read it
please help
Problem is in the action of your form, you have entered the wrong URL in the action
You have to put home URL instead of read/, because you are handling your form submission in your home function so replace your form action by this
<form method="POST" action="{% url 'Home' %}" enctype="multipart/form-data">
{%csrf_token%}
{{form}}
<button type=submit>click to submit</button>
</form>

Prepopulating a textarea element with Flask

I am trying to write a program that reads a file and outputs it to the textarea. The user can then edit the file and then click the submit button in order to submit the changes.
Currently, I have a method of obtaining the user's input (request.form), however I do not know how to prepopulate the text area element.
Flask
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__)
#app.route('/')
def hello():
return render_template("index.html")
#app.route('/', methods=['POST'])
def submit():
return 'You entered: {}'.format(request.form['whitelist'])
if __name__ == '__main__':
app.run(host="localhost", port=8000, debug=True)
HTML
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Index</title>
</head>
<body>
<h1 style="color: blue">Index</h1>
<p>This is an HTML file served up by Flask</p>
<p>Whitelist:</p>
<form action="{{ url_for('submit') }}" method="post">
<textarea id="whitelist" name="whitelist" rows="4" cols="50"></textarea>
<input type="submit">
</form>
</body>
</html>
So is their a method that exists such that one can prepopulate the textarea?
Example
my_file_data = read_my_file(file)
Flask.output(element_id = "whitelist", input = my_file_data)
Implementing Solution
Try the following changes in your code (i assume that your file is a .txt but it can work with other file types with some changes):
Flask
#app.route('/')
def hello():
with open('your_file') as f:
t=f.read()
return render_template("index.html", t=t)
HTML
<textarea id="whitelist" name="whitelist" rows="4" cols="50"> {{t}} </textarea>

Why am I getting a 500 error with this code?

I am trying to create a site with a webform using Flask, but I keep getting a 500 error
Here is my template/main.html
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample Page</title>
<meta name="viewport" content="width=device-width"
initial=scale=1/>
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='favicon.ico') }}" rel="shortcut icon">
</head>
<h2>Hello, this site is meant to test my fill_web_form.py script</h2>
<br>
<br>
<h1>Test Form</h1>
<form action="/" method="post" name="login">
{{ render_field(form.test_form) }}<br>
<p><input type="submit" value="Sign In"></p>
</form>
</html>
Here is my init.py file
from flask import Flask, render_template
#import sqlite3
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("main.html")
if __name__ == "__main__":
app.run()
Here is my form.py file
from flask.ext.wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class LoginForm(Form):
test_form = StringField('test_form', validators=[DataRequired()])
Why do I keep getting a 500 error? I cant figure it out.
Run in debug mode app.run(debug=True) to see more information in browser.
You should import form and send to template. You may need secret_key to use csrf. etc.
from form import LoginForm
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
#app.route('/')
def homepage():
return render_template("main.html", form=LoginForm())

Categories

Resources