ml model on django and html - python

I have
index.html
<p>input an image</p>
<p>
<form>
<input type="file" name="pic" accept="image/.jpg" onchange="loadFile(event)"></input>
<img id="output"/>
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
};
</script>
</form>
</p>
<p>
<form>
<input type="submit" value="result"></input>
</form>
</p>
views.py
from django.shortcuts import render
def test(request):
if request.POST:
d = request.POST.dict()
img = d.get("pic")
a=image_array(img) # convert image to array use to test model
r=model(a) #
return render(request, "./index.html",r)
else:
return render(request, "./index.html")
how can I show the result of predict below the submit button?

Related

Forms django -> is_valid

I am currently developping an application on django and when i send a post request from a form, is_valid method return false, but form.is_bound return True.
my form.error -> mailThis field is required.prenomThis field is required.nomThis field is required.
my forms.py
from django import forms
class formadduser(forms.Form):
mail = forms.CharField(label='Mail', max_length=40)
# imput_username = forms.CharField(input='input_username', max_length=100)
prenom = forms.CharField(label='Prénom', max_length=25)
# input_password = forms.CharField(input='input_pathword', max_length=100)
nom = forms.CharField(label = 'Nom', max_length=25)
views.py where i'm trying to get the form inputs:
from re import S
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, QueryDict
from .forms import formadduser
import pickle
import os
from .fonctions import tri
from .models import Users
# Create your views here.
def administrator(request) :
# test = request.POST[username]
# print(test)
# request.form['username'] je crois que c'est du flask
return render(request, 'admin.html')
def index(request):
if request.method == 'POST':
var = request.POST["username"]
print(var)
text = """<h1>{{var}}</h1>
<p>les crepes nananinanana</p>"""
return HttpResponse(text)
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = formadduser(request.POST)
print(form)
# check whether it's valid:
if form.is_valid():
print("debug")
print(form.cleaned_data["mail"])
var = Users(mail = form.cleaned_data["Mail"], prenom = form.cleaned_data["Prenom"], nom = form.cleaned_data["Nom"])
var.save()
# process the data in form.cleaned_data as required
# ...
# print(NameForm.username)
# redirect to a new URL:
# return HttpResponseRedirect('/thanks/')
# Username = form.cleaned_data
# text = """<h1>{{form.cleaned_data["username"]}}</h1>
# <p>les crepes nananinanana</p>"""
# return HttpResponse(text)
# print(form.cleaned_data["username"])
# u = USERS(Username = form.cleaned_data["username"], droits = form.cleaned_data["droits"])
# u.save()
# query = pickle.loads("zeubi")
# test = list(USERS.objects.values("Username"))
# test = USERS.objects.values("Username")
# test = USERS.objects.all()
# test = str(USERS.objects.values("droits"))
# res = tri(test)
# user_qs = USERS.objects.all()
# for user in user_qs:
# print(user['Username'])
# testv = QueryDict
# test.query = query
return render(request, 'admin.html')
# return render(request, 'admin.html', {'test' : test})
# return(locals())
# USERS.Username = form.cleaned_data["username"]
# return form.cleaned_data
else:
print("invalid form")
print(form.is_bound)
# print(form.errors)
# if a GET (or any other method) we'll create a blank form
else:
print("error")
form = formadduser()
return render(request, 'admin.html', {'form': form})
templates.py with 4 forms but my test is on formadduser:
<!DOCTYPE html>
<html lang="fr">
<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>ADMIN</title>
{% load static %}
<script src="{% static 'global/jquery.js' %}"></script>
<script src="{% static 'administrator/admin.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'administrator/admin.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'global/StyleGlobal.css' %}">
</head>
<body id="idbody" onclick="fout();foutform()">
<div class="bande">
<div onclick="testhb()" id="hb">
<div class="barre"></div>
<div class="barre"></div>
<div class="barre"></div>
<ul id="ulmenu">
<li class="menu"><a class="textdeco" href="http://10.75.101.201/Front/mat/mat.html">Materiel</a></li>
<li class="menu"><a class="textdeco" href="http://10.75.101.201/Front/offrecgr/offrecgr.html">Offres/CGR</a></li>
</ul>
</div>
<!-- </div> -->
<div class="logo">
<img src="{% static 'global/GHD.png' %}" alt="Logo">
<!-- -->
</div>
</div>
<div class="titre">
<h1 class="accueiltxt">ADMIN</h1>
</div>
<div class="gigacontainer" id="gigacontainer">
<div class="containerbutton">
<div class="button" id="buttonsuppuser" onclick = "buttonsuppuser()">
<p class="trashcan">🗑</p></div>
<div class="button" id="buttonadduser" onclick="buttonadduser()">+</div>
<div class="txtbutton">Users</div>
<div class="button" id="buttonsuppapp" onclick = "buttonsuppapp()">🗑</div>
<div class="button" id="buttonaddapp" onclick = "buttonaddapp()">+ </div>
<div class="txtbutton">Apps</div>
</div>
<form action="" method="post" class="form" id="formsuppuser">
{% csrf_token %}
<label for="suppuser">Username</label>
<input type="text" name="suppuser" id="suppuser">
<button>Supprimer</button>
</form>
<form name="formadduser" action="" method="post" class="form" id="formadduser">
{% csrf_token %}
<label for="addusermail">Mail</label>
<input required="required" type="text" name="addusermail" id="addusermail">
<label for="adduserprenom">Prénom</label>
<input required="required" type="text" name="adduserprenom" id="adduserprenom">
<label for="addusernom">Nom</label>
<input required="required" type="text" name="addusernom" id="addusernom">
<button type="submit">Ajouter</button>
</form>
<form action="" method="post" class="form" id="formsuppapp">
{% csrf_token %}
<label for="suppapp">Application</label>
<input type="text" name="suppapp" id="suppapp">
<button>Supprimer</button>
</form>
<form action="" method="post" class="form" id="formaddapp">
{% csrf_token %}
<label for="addapp">Application</label>
<input type="text" name="addapp" id="addapp">
<button>Ajouter</button>
</form>
</div>
</html>
You should have the errors in form.errors, without them, we cannot tell you anything.
It may also be that your form is not bound (request data have not be sent to the form). You can check this with form.is_bound.
If this return false, you did not send your data into your form:
form = MyForm(data=request.POST)
You can see how is_valid works in the django source.
As you can see, you can know whats wrong juste by checking form.is_bound or form.errors.

upload a file and get celery progress bar using ajax in django

I want to upload a file, process it in a Celery task, and show a progress bar using AJAX. but I did not get the solution. Can you help me with this task?
Views.py
# Create your views here.
def index(request):
if request.method == 'POST':
myfile =request.FILES['file']
fs = FileSystemStorage()
filename = fs.save(myfile.name , myfile)
uploaded_file_url = fs.url(filename)
data = process_file.delay(myfile.name)
task_id=data.task_id
return render(request , 'index.html', context={'task_id':task_id})
else:
return render(request , 'index.html')
task.py
def task_status(request, task_id):
if 'task' in request.GET:
task_id = request.GET['task_id']
else:
return HttpResponse('no job id given')
task = AsyncResult(task_id)
data = {
'state': task.state,
'result': task.result,
}
return HttpResponse(json.dumps(data), content_type='application/json')
# return render(request, 'progress.html', data)
Task.py
#shared_task(bind=True)
def process_file(self, file_name):
print('Uploading image...')
progress_recorder = ProgressRecorder(self)
result = 0
for i in range(5):
time.sleep(1)
result += i
instance = Tooltype(image=file_name)
instance.save()
#fs.delete(file_name)
print('Uploaded!')
progress_recorder.set_progress(i + 1, 5)
return result
index.html
<body>
<h1>select your file to process it!</h1>
<div class='progress-wrapper'>
<div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;"> </div>
</div>
<div id="progress-bar-message">Waiting for progress to start...</div>
<form id="process-raw-data" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" id="file" name="file" >
<button type="submit" class="btn btn-success">Submit</button>
</form>
{% if task_id %}
<script>
var progressUrl = "{% url 'celery_progress:task_status' task_id %}";
function customResult(resultElement, result) {
$( resultElement ).append(
$('<p>').text('Sum of all seconds is ' + result)
);
}
$(function () {
CeleryProgressBar.initProgressBar(progressUrl, {
onResult: customResult,
})
});
</script>
{% endif %}
<script src="{% static 'celery_progress/celery_progress.js' %}"></script>
<script src="{% static 'assets/js/main.js' %}"></script>
</body>
when i upload a file and click on submit button it shows the progress bar but the file not shown in page and the task is successed and image is not uploading and show on page.
[2022-04-20 15:37:52,815: INFO/MainProcess] Task toolapp.tasks.process_file[b219aba3-d170-49e2-925c-3ad1c0a7c54b] succeeded in 5.327999999979511s: 10
thanks and got stuck on this task please help me.

request.POST not reading form data in django

I have my views file:
from django.shortcuts import render
from .models import Note
# Create your views here.
def index(request):
return render(request, "index.html", {})
def write(request):
notes = Note.objects
return render(request, "write.html", {})
def create(request):
if request.POST:
body = request.POST['note']
title = request.POST['title']
print(f'title = { title }\nbody = { body }'
and my html code:
<h1>CREATE A NOTE</h1>
<form action="{% url 'notes:create' %}" method="post">
{% csrf_token %}
<label for="title">Title</label>
<input type="text" name="title"><br>
<label for="note">Note</label>
<input type="text" name="note"><br>
<input type="submit" value="Submit">
</form>
Whenever I submit this form and try to access either the title or note values I get a MultiValueDictKeyError
A MultiValueDictKeyError comes when you try to access something from request.POST which doesn't exist. It's basically the same the python KeyError. Use request.POST.get('key', 'default_if_key_doesn't exist')
def create(request):
if request.POST:
body = request.POST.get('note', '')
title = request.POST('title', '')
print(f'title = { title }\nbody = { body }'

File object not saving to disk

This is my views.py
from django.shortcuts import render
# Create your views here.
from forms import DocumentForm
from models import Document
def SaveDocument(request):
saved = False
if request.method == "POST":
#Get the posted form
MyDocumentForm = DocumentForm(request.POST, request.FILES)
if MyDocumentForm.is_valid():
print 'It enters here'
document = Document()
document.name = MyDocumentForm.cleaned_data["name"]
document.document = MyDocumentForm.cleaned_data["document"]
print document.document
document.save()
saved = True
else:
print 'Fails'
else:
MyDocumentForm = DocumentForm()
return render(request, 'saved.html', locals())
profile.html
<html>
<body>
<form name = "form" enctype = "multipart/form-data"
action = "{% url "SaveDocument" %}" method = "POST" >{% csrf_token %}
<div style = "max-width:470px;">
<center>
<input type = "text" style = "margin-left:20%;"
placeholder = "Name" name = "name" />
</center>
</div>
<br>
<div style = "max-width:470px;">
<center>
<input type = "file" style = "margin-left:20%;"
placeholder = "document" name = "document" />
</center>
</div>
<br>
<div style = "max-width:470px;">
<center>
<button style = "border:0px;background-color:#4285F4; margin-top:8%;
height:35px; width:80%; margin-left:19%;" type = "submit" value = "Login" >
<strong>Login</strong>
</button>
</center>
</div>
</form>
</body>
</html>
The code works perfectly fine but it does not seem to save the file to disk. Printing the document shows that there is a document.
May i know what i did wrongly? i was following this example with minor changes
Need a minimal Django file upload example
in this line document.document = MyDocumentForm.cleaned_data["document"]

Django- why after using ajax, it becomes an empty page

The function on the page:
user enter some information on the form
without refreshing, the right side can show some query result(sales) based on user entry
Before adding the ajax function, the page can display the form and the table. But after using the ajax, the page becomes empty.
Can anyone help check what is the reason? Thanks in advance.
url
url(r'^result_list/$',ResultView.as_view(),name='result'),
models.py
class Input(models.Model):
company=models.CharField(max_length=100)
region=models.CharField(max_length=100)
class Result(models.Model):
sales=models.IntegerField(blank=False,null=False)
views.py
from django.views.generic.list import ListView
from django.core import serializers
class ResultView(ListView):
context_object_name = 'result_list'
template_name = 'result_list.html'
def get_queryset(self):
return Result.objects.all()
def post(self, request, *args, **kwargs):
form = InputForm(request.POST)
if form.is_valid():
if self.request.is_ajax():
company = form.cleaned_data['company']
region = form.cleaned_data['region']
queryset=Result.objects.filter(region=region).aggregate(Sum('sales'))
return HttpResponse(json.dumps(queryset))
else:
return HttpResponse(form.errors)
'''def get_context_data(self, **kwargs):
context = super(ResultView, self).get_context_data(**kwargs)
context["sales"] = self.get_queryset().aggregate(Sum('sales'))'''
html
<style>...CSS part
</style>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#InputForm").submit(function() { // catch the form's submit event
var region= $("#id_region").val();
var company= $("#id_company").val();
$.ajax({
data: $(this).serialize(), // get the form data
type: $(this).attr('post'),
dataType: 'json',
url: "dupont_list/",
success: function(data) {
var html = "<table>"
html += "<td>"+data['sales__sum']+"</td>"
html += "</table>"
$("#result").html(html);
html += "</table>"
$("#result").html(html);
}
return false;
});
})
</script>
<form id="InputForm" method="post" action=""> #here is the data entry form
{% csrf_token %}
<!--enter the company name-->
<div class="field">
{{ form.company.errors }}
<label id="id_company" name="company" for="{{ form.company.id_for_label }}">Company:</label>
{{ form.company }}
</div>
<!--select region-->
<div class="field" >
<label> Select the Region:
{{ form.region }}
{% for region in form.region.choices %}
<option value="region" name= "region" id="id_region">{{region}} </option>
{% endfor %}
</label>
</div>
<!--submit-->
<p><input type="button" value="Submit" /></p></div>
</form>
</div>
<div id="result" class="result"> <!--Showing the filtered result in database-->
<table>
<tr><b>Sales</b></tr>
<td> {{sales.sales__sum}}</td>
<tr><b>Employee</b></tr>
<td> {{employee.employee__sum}}</td>
</table>
I would go with a FormView:
class ResultView(FormView):
context_object_name = 'result_list'
template_name = 'result_list.html'
form_class = InputForm
def get_context_data(self, **kwargs):
context = super(ResultView, self).get_context_data(**kwargs)
context["results"] = Result.objects.all()
context["sales"] = context.results.aggregate(Sum('sales'))
return context
def form_valid(self,form):
company = form.cleaned_data['company']
region = form.cleaned_data['region']
queryset = Result.objects.filter(region=region).aggregate(Sum('sales'))
return HttpResponse(json.dumps(queryset))
This way you're bypassing the get_context_data and get_queryset methods if the form is valid and return a custom content response.

Categories

Resources