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"]
Related
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.
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 }'
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?
I wrote codes, but I don't know how to set 'name' and 'value' of hidden tag with Django template. I read Django's Widgets Docs, but I couldn't find the way.
(Pdb) print(errors)
<ul class="errorlist"><li>friend_id<ul class="errorlist"><li>This field is required.</li></ul></li><li>add_remove<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
First, I tried to write like
<input type="hidden" name="friend_id" value="{{ user_info.user_id }}">
and
friend_id = request.POST.friend_id
But I couldn't get how to get POST values without Django's Form. So, I used Django's Form with following codes.
views.py
from myapp.forms import HiddenUserPage
hiddenform = HiddenUserPage
if request.method == 'POST':
hidden = hiddenform(request.POST)
if hidden.is_valid():
from myapp.models import Friends
try:
friend_id = hidden.cleaned_data['friend_id']
add_remove = hidden.cleaned_data['add_remove']
if add_remove == "add":
f = Friends(user_id=request.user.user_id, friend_id=friend_id)
f.save()
elif add_remove == "remove":
f = Friends.objects.filter(user_id=request.user.user_id).get(friend_id=friend_id)
f.delete()
except:
errors = "DB error"
else:
errors = hidden.errors
else:
hidden = hiddenform()
errors = ""
view = {
'errors': errors,
'hidden': hidden,
}
template = 'myapp/user/user_page.html'
return render(request, template, view)
forms.py
class HiddenUserPage(forms.Form):
friend_id = forms.CharField(widget=forms.HiddenInput())
add_remove = forms.CharField(widget=forms.HiddenInput())
user_page.html
<form method="POST" action="" class="">
{% csrf_token %}
<p class="submit">
<button class="confirmbutton" type="submit">
{% if is_friend %}
remove friend
<!-- # I'd like to write like # -->
<!-- <input type="hidden" name="friend_id" value="remove"> # -->
<!-- <input type="hidden" name="friend_id" value="{{ user_info.user_id }}"> # -->
{{ hidden.add_remove }}
{{ hidden.friend_id }}
{% else %}
add friend
<!-- <input type="hidden" name="friend_id" value="add"> # -->
<!-- <input type="hidden" name="friend_id" value="{{ user_info.user_id }}"> # -->
{{ hidden.add_remove }}
{{ hidden.friend_id }}
{% endif %}
</button>
</p>
</form>
Sorry, my code is filthy.
Looks like the question is in providing initial data to the form, then it's is generally done in the view passing initial to the form instantiation, e.g.:
# In your view.py
def ...(...):
# Inside your view function
if request.method == 'GET':
# Provide initial data to the form here
# Get your 'user_info' from models or sessions,
# or wherever you keep it
hidden = hiddenform(initial={"friend_id":user_info.user_id})
if reuest.method == 'POST':
hidden = hiddenform(request.POST)
# Process posted form data
...
# More code general for both HTTP verbs
view = {'errors': errors, 'hidden': hidden}
template = 'myapp/user/user_page.html'
return render(request, template, view)
You might also want to bound the form to model data directly, see the docs for more info.
I am trying to write a condition where if 1st part is ok then 2nd part will show.I wrote my forms.py in a following way :
class SubmissionForm(forms.Form):
first_name=forms.CharField(max_length=120, required=True)
last_name=forms.CharField(max_length=120, required=True)
class UploadForm(forms.Form):
file1 = forms.Field(label='File1', widget = forms.FileInput,required = True )
file2 = forms.Field(label='File1', widget = forms.FileInput, required = True )
In my views.py:
def submission(request):
validform=False
title="Please submit your data"
form = SubmissionForm(request.POST)
contextsumission={"title":title, "form":form}
if form.is_valid():
first_name = form.cleaned_data.get("first_name")
last_name = form.cleaned_data.get("last_name")
validform=True
if validform:
contextupload={"title":"Please upload your files","valid":True}
return render(request, 'submission.html', contextupload)
form2 = UploadForm(request.FILES)
contextsumission={"title":'Upload files', "form2":form2}
if form2.is_valid():
file1 = form2.request.FILES.get("file1")
file2 = form2.request.FILES.get("file2")
contextsumission={"title":"Thank you for your data submission"}
return render(request, 'submission.html', contextsumission)
And I have tried to write my template in a following way
{% if valid %}
<h1 class ='text-align-center', style="color: blue;"> {{ title }} </h1>
<form method ='POST' enctype="multipart/form-data" action =''> {% csrf_token %}
{{form2|crispy}}
<input class='btn btn-primary', type='submit', value='Upload'>
</form>
{% else %}
<h1 class ='text-align-center', style="color: blue;"> {{ title }} </h1>
<form method ='POST' enctype="multipart/form-data" action =''> {% csrf_token %}
{{form|crispy}}
<input class='btn btn-primary', type='submit', value='Submit'>
</form>
{% endif %}
I can see my SubmissionForm clearly in template but after pressing submit button I want to show file upload form but it is not working.
Anyone can please tell me where I need to change my code?
Thanks
Paul
Yes I have realized that and modified my code but still I have problem and def submission function is not validating two forms!! That means when ever I am trying to do form2.is_valid(), is returning false.
def submission(request):
title="Please submit your data"
form = SubmissionForm(request.POST)
contextsubmission={"title":title, "form":form}
if form.is_valid():
first_name = form.cleaned_data.get("first_name")
last_name = form.cleaned_data.get("last_name")
form2 = UploadForm(request.FILES)
contextsubmission ={"title":"Please upload your files","form2":form2,"valid":True}
if form2.is_valid():
file1 = form2.request.FILES.get("file1")
file2 = form2.request.FILES.get("file2")
contextbsumission={"title":"Thank you for your data submission"}
return render(request, 'submission.html', contextsubmission)