how to us the prefix? - python

I try to upload two forms with one submit button.
A user can select a pdf file and a excel file. And then uploading both files. And then the contents of both are returned.
So I try to upload both files with one submit button.
But the two selected file options are not visible for uploading the files.
So I have the template like this:
{% extends 'base.html' %} {% load static %} {% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Create a Profile</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" />
</head>
<body>
<div class="container center">
<span class="form-inline" role="form">
<div class="inline-div">
<form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data">
<div class="d-grid gap-3">
<div class="form-group">
{% csrf_token %}
{{ form.0.as_p }}
<button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button>
</div>
<div class="form-outline">
<div class="form-group">
<textarea class="inline-txtarea form-control" id="content" cols="70" rows="25">
{{content}}</textarea>
</div>
</div>
</div>
<div class="d-grid gap-3">
<div class="form-group">
{{ form.1.as_p }}
</div>
<div class="form-outline">
<div class="form-group">
<textarea class="inline-txtarea form-control" id="content" cols="70" rows="25">
{{conten_excel}}</textarea>
</div>
</div>
</div>
</form>
</div>
</span>
</div>
</body>
</html>
{% endblock content %}
and the views.py:
class ReadingFile(View):
def get(self, *args, **kwargs):
return render(self.request, "main/controle_punt140.html", {
"form1": UploadFileForm(),
"form2": ExcelForm()
})
def post(self, *args, **kwargs):
filter_text = FilterText()
types_of_encoding = ["utf8", "cp1252"]
form1 = UploadFileForm(
self.request.POST, self.request.FILES, prefix="form1")
form2 = ExcelForm(self.request.FILES,
self.request.FILES, prefix="form2")
content = ''
content_excel = ''
if form1.is_valid() and form2.is_valid() and self.request.POST:
uploadfile = UploadFile(image=self.request.FILES["upload_file"])
excel_file = self.request.FILES["upload_file"]
uploadfile.save()
for encoding_type in types_of_encoding:
with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f:
if uploadfile.image.path.endswith('.pdf'):
content = filter_text.show_extracted_data_from_file(
uploadfile.image.path)
else:
content = f.read()
if uploadfile.image.path.endswith('xlsx'):
wb = openpyxl.load_workbook(excel_file)
worksheet = wb['Sheet1']
print(worksheet)
excel_data = list()
for row in worksheet.iter_rows():
row_data = list()
for cell in row:
row_data.append(str(cell.value))
excel_data.append(row_data)
print(excel_data)
content_excel = excel_data
else:
content_excel = f.read()
return render(self.request, "main/controle_punt140.html", {
'form1': ExcelForm(),
'form2': UploadFileForm(),
"content": [content, content_excel]
})
# I've adjusted the indent here to what I think it should be.
return render(self.request, "main/controle_punt140.html", {
"form1": form1,
"form2": form2,
})
and forms.py:
class UploadFileForm(forms.Form):
upload_file = forms.FileField(required=False)
class ExcelForm(forms.Form):
upload_file = forms.FileField(required=False)
urls.py:
urlpatterns = [
path('', views.starting_page, name='starting_page'),
path('controlepunt140', views.ReadingFile.as_view(), name='controlepunt140'),
]

The variable name used in the template is the key of the dictionary, not the value. The value is what is inserted into the template when django renders the page.
You have {{form1.as__p}} in your template, but you send "form": [form1, form2] as your context, so the variable in the template should be {{ form.0.as_p }} and {{ form.1.as_p }}. I haven't tested this, but if it doesn't work, you could just send the two forms separately like:
from django.shortcuts import redirect
class ReadingFile(View):
def get(self, *args, **kwargs):
return render(self.request, "main/controle_punt140.html", {
"form1": UploadFileForm(),
"form2": ExcelForm()
})
def post(self, *args, **kwargs):
filter_text = FilterText()
types_of_encoding = ["utf8", "cp1252"]
form1 = UploadFileForm(self.request.POST, self.request.FILES, prefix="form1")
form2 = ExcelForm(self.request.FILES, self.request.FILES, prefix="form2")
content = ''
content_excel = ''
if form1.is_valid() and form2.is_valid() and self.request.POST:
uploadfile = UploadFile(image=self.request.FILES["upload_file"])
excel_file = self.request.FILES["upload_file"]
uploadfile.save()
for encoding_type in types_of_encoding:
with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f:
if uploadfile.image.path.endswith('.pdf'):
content = filter_text.show_extracted_data_from_file(
uploadfile.image.path)
else:
content = f.read()
if uploadfile.image.path.endswith('xlsx'):
#Uploading excel form:
#this is just logic.
pass
else:
content_excel = f.read()
# You probably should do a redirect after the form is
# submitted, rather than render the page.
return redirect('main:controlepunt140')
# return render(self.request, "main/controle_punt140.html", {
'form1': ExcelForm(),
'form2': UploadFileForm(),
"content": [content, content_excel]
})
# I've adjusted the indent here to what I think it should be.
return render(self.request, "main/controle_punt140.html", {
"form1": form1,
"form2": form2,
})
You probable should also change to a redirect after the form is submitted and saved successfully. Check out Post/Redirect/Get and/or rendering content after a succesful post request.
Edit
Changed template to use {{ form.0.as_p }} as indicated by #nigel239
You can redirect to the same page where the form was submitted, so if the user hits the refresh button on their browser for some reason, you will not get an alert box asking the user to resend the form.

Related

Two forms on same template in django. How to collaborate the template with the views.py?

I have a template with two forms like this and two textareas where the uploaded content will be returned:
<form
class="form-inline"
role="form"
action="/controlepunt140"
method="POST"
enctype="multipart/form-data"
id="form_pdf"
>
<div class="form-group">
{% csrf_token %} {{ form_pdf }}
<button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button>
</div>
</form>
<div class="form-outline">
<div class="form-group">
<textarea class="inline-txtarea form-control" cols="70" rows="25">
{{content}}</textarea
> <form
class="form-inline"
role="form"
action="/controlepunt140"
method="POST"
enctype="multipart/form-data"
id="form_excel"
>
<div class="form-group">
{% csrf_token %} {{ form }}
<button type="submit" name="form_excel" class="btn btn-warning">Upload!</button>
</div>
</form>
<textarea class="inline-txtarea form-control" cols="65" rows="25">
{{content_excel}}</textarea
>
and the views.py:
class ReadingFile(View):
def get(self, request):
form = ProfileForm()
return render(request, "main/controle_punt140.html", {
"form": form
})
def post(self, request):
types_of_encoding = ["utf8", "cp1252"]
submitted_form = ProfileForm(request.POST, request.FILES)
content = ''
if submitted_form.is_valid():
uploadfile = UploadFile(image=request.FILES["upload_file"])
name_of_file = str(request.FILES['upload_file'])
uploadfile.save()
for encoding_type in types_of_encoding:
with open(os.path.join(settings.MEDIA_ROOT,
f"{uploadfile.image}"), 'r', encoding=encoding_type) as f:
if uploadfile.image.path.endswith('.pdf'):
pass
else:
content = f.read()
return render(request, "main/controle_punt140.html", {
'form': ProfileForm(),
"content": content
})
return render(request, "main/controle_punt140.html", {
"form": submitted_form,
})
and forms.py:
class ProfileForm(forms.Form):
upload_file = forms.FileField()
and urls.py:
urlpatterns = [
path('', views.starting_page, name='starting_page'),
path('controlepunt140', views.ReadingFile.as_view(), name='controlepunt140')
]
So this works for the first upload function(pdf). The output is returned to the textarea.
But how to have it also work with the second upload function content_excel?
I.E: how to distinguish the two upload functions?
So this part:
return render(request, "main/controle_punt140.html", {
'form': ProfileForm(),
"content": content
})
return render(request, "main/controle_punt140.html", {
"form": submitted_form,
})
Would be double? one for pdf and one for excel
According to the name of the submit buttons:
#FORM PDF
<button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button>
#FORM EXCEL
<button type="submit" name="form_excel" class="btn btn-warning">Upload!</button>
So, in your views.py you can distinguish them on this way:
if request.POST.get('form_pdf'):
....
elif request.POST.get('form_excel'):
....

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.

How to update form element data value after construction using multidict

I have a website post creator / editor im writing. I have successfully been able to create post (saves to json) , get a pull down menu list of the made post from same db (and a second, all posts.json, which is where the list of posts comes from. ), and have the element forms populated with said information. I can then save it, and it is indeed writing to the file. Problem is , the data in the text fields is not updating in saved post. It saves the original data passed with the multidict. I CAN manually update it as : Ex. form.title.data = "New Title" , and it saves as such, so i know its handling everything correctly on the save end. If anyone has an idea how to get the updated information from the form fields, id be grateful. Thank you.
Constructors at line 103
Code:
https://hastebin.com/lafavifike.py
from flask import Flask, render_template, request, flash, redirect, url_for
from QFlask import QFlask
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired
from wtforms.fields import Field, TextAreaField, TextField, SelectField
from wtforms.widgets import TextArea
import os, json
from werkzeug.datastructures import MultiDict
app = Flask(__name__)
app.config['SECRET_KEY'] = "test"
class editPostForm(FlaskForm):
id_pos = ['blog_posts', 'security_posts', 'game_posts','music_posts','project_posts']
file_path_all = str(os.getcwd()) + "\\static\\allposts.json"
with open(file_path_all, 'r') as post_edit:
all_posts = json.load(post_edit)
posts = [('default', 'Choose Post To Edit')]
for key in all_posts.keys():
if key not in id_pos:
posts.append((all_posts[key]['id'], all_posts[key]['title']))
loadform = SelectField('Choose Post', choices=posts)
loadposts = SubmitField('Load')
class PostForm(FlaskForm):
#Actual form fields
categories = [('blog_posts','Blog Post'), ('security_posts','Security Post'),('game_posts','Games Post'),('music_posts','Music Post'),('project_posts','Projects Post')]
category = SelectField('Category', choices = categories, validators = [DataRequired()])
title = StringField('Title', validators=[DataRequired()])
date = StringField('Date', validators=[DataRequired()])
content = TextAreaField('Content', validators=[DataRequired()], widget=TextArea())
submit = SubmitField('Submit')
#app.route('/', methods=['POST', 'GET'])
def index():
file_path = str(os.getcwd()) + "\\static\\posts.json"
with open(file_path, 'r+') as post_edit:
data = json.load(post_edit)
positions = {}
for key in data['id_pos'].keys():
positions[key] = data['id_pos'][key]
#Create Post Form
prefixs = {'1':'blog_posts','2':'security_posts',"3":"game_posts","4":"music_posts","5":"project_posts"}
form = PostForm()
edit_form = editPostForm()
if request.method == 'POST':
print(edit_form.loadform.data)
if edit_form.loadform.data != 'None':
return redirect('/edit_post/'+ edit_form.loadform.data)
else:
form.validate()
category = form.category.data
title = form.title.data
date = form.date.data
content = form.content.data
post_id = str(int(positions[category]) +1)
post = {
"id": post_id,
"title": title,
"date": date,
"content": content
}
#Update data structure, and save back to the file
data['id_pos'][category] = post_id
data[category][post_id] = post
#SAVE POST
data['index_posts'][post_id] = post
with open(file_path, 'w') as post_edit:
json.dump(data, post_edit)
print('Post Saved')
flash('Post Saved')
file_path_all = str(os.getcwd()) + "\\static\\allposts.json"
with open(file_path_all, 'r+') as file:
data = json.load(file)
with open(file_path_all, 'w') as file:
data[post_id] = post
json.dump(data, file)
return redirect(url_for('index'))
return render_template('post_editor.html', title="Post Creator", form=form, edit_form = edit_form)
#app.route('/edit_post/<id>', methods=['GET','POST'])
def edit_post(id):
#Load data from JSON Files. posts= categorized posts, allposts is all posts key'd by id.
file_path_all = str(os.getcwd()) + "\\static\\allposts.json"
file_path = str(os.getcwd()) + "\\static\\posts.json"
with open(file_path, 'r+') as post_edit:
data = json.load(post_edit)
with open(file_path_all, 'r') as post_edit:
all_posts = json.load(post_edit)
posts = [('default', 'Choose Post To Edit')]
for key in all_posts.keys():
posts.append((all_posts[key]['id'], all_posts[key]['title']))
#Auto filling category and data for fields
prefixs = {'1':'blog_posts','2':'security_posts',"3":"game_posts","4":"music_posts","5":"project_posts"}
category = prefixs[id[0]]
form = PostForm(MultiDict([("id", id),("title", data[category][str(id)]['title']) ,("date", data[category][str(id)]['date']),("content" , data[category][str(id)]['content'])]))
if request.method == "POST":
form.validate()
data[category][str(id)] = {
'id': str(id),
'title': form.title.data,
'date': form.date.data,
'content': str(form.content.data)
}
all_posts[str(id)] = {
'id': str(id),
'title': form.title.data,
'date': form.date.data,
'content': str(form.content.data)
}
#Write to file.
print('Saving the edited post..')
with open(file_path_all, 'w') as file:
json.dump(all_posts,file)
print('File Saved ')
with open(file_path, 'w') as file:
json.dump(data,file)
flash('File Saved')
return redirect('/')
return render_template('edited_post.html', title="Post Editor", form = form)
if __name__ == '__main__':
QFlask(app).run(title="Web Post Editor", zoom=0, width=600, height= 600)
posteditor.html
<html>
<head><title> Post Editor</title>
<style src="{{url_for('static', filename='css/bootstrap.min.css')}}"></style>
<style>
pre{
content-align: left;
}
body{
color: grey;
background-image: url({{url_for('static', filename='img/editor-bg.jpg')}});
}
</style>
<script src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
<script src="{{url_for('static', filename='js/popper.js')}}"></script>
<script src="{{url_for('static', filename='js/bootstrap.min.js')}}"></script>
</head>
<body>
<div class="container">
{% with message = get_flashed_messages()%}
<ul class="flashes">
{{message}}
</ul>
{% endwith%}
{{ form.csrf_token }}
<form method="POST" action="" id="selection">
<fieldset class="form-group">
<div class="form-group">
{{edit_form.loadform.label(class="form-control-label")}}
{{ edit_form.loadform(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ edit_form.loadposts(class="btn btn-outline-info")}}
</div>
</fieldset>
</form>
<form method="POST" action="">
<fieldset class="form-group">
<div class="form-group">
{{ form.category.label(class="form-control-label")}}
{{ form.category(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.title.label(class="form-control-label")}}
{{ form.title(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.date.label(class="form-control-label")}}
{{ form.date(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.content.label(class="form-control-label")}}
{{ form.content(cols="50", rows="20",class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</fieldset>
</form>
</div>
</body>
</html>
editedpost.html:
<html>
<head><title> Post Editor</title>
<style src="{{url_for('static', filename='css/bootstrap.min.css')}}"></style>
<style>
pre{
content-align: left;
}
body{
color: grey;
background-image: url({{url_for('static', filename='img/editor-bg.jpg')}});
}
</style>
<script src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
<script src="{{url_for('static', filename='js/popper.js')}}"></script>
<script src="{{url_for('static', filename='js/bootstrap.min.js')}}"></script>
</head>
<body>
<div class="container">
{% with message = get_flashed_messages()%}
<ul class="flashes">
{{message}}
</ul>
{% endwith%}
<form method="POST" action="">
{{ form.csrf_token }}
<fieldset class="form-group">
<div class="form-group">
{{ form.category.label(class="form-control-label")}}
{{ form.category(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.title.label(class="form-control-label")}}
{{ form.title(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.date.label(class="form-control-label")}}
{{ form.date(class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.content.label(class="form-control-label")}}
{{ form.content(cols="50", rows="20",class="form-control form-control-lg")}}
</div>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</fieldset>
</form>
</div>
</body>
</html>
I found the answer(with the help of some IRC folk ).The problem was the form data was always pulling from the initialized version. It never requested the update from the page. in data[category][str(id)] = , the values should be updated via request.form.get('title')

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.

Django form won't show up on template

I'm making a sign in system in Django Python, i've been preparing the forms.py, views.py and the template itself, but so far the form fail to load on the template, can anyone help?
Forms.py
class Email_Only_SignUp_Form(forms.Form):
email = forms.EmailField(initial='Your Email...')
Views.py
def email_only_signup_form(request, template_name):
if request.method == 'POST':
signup_form = Email_Only_SignUp_Form(request.POST)
if signup_form.is_valid():
email = signup_form.cleaned_data['email']
username = email
try:
#check for duplicate username
User.objects.get(username=username)
email_error = 'email already exist'
except:
#initial creation of user object
try:
import os, random, string
length = 13
chars = string.ascii_letters + string.digits + '!#$()'
random.seed = (os.urandom(1024))
password = ''.join(random.choice(chars) for i in range(length))
User.objects.create_user(username,
username,
password,
)
user = User.objects.get(username=username)
user_profile=UserProfile(user=user)
user_profile.save()
#send email to user
try:
admin_email = settings.EMAIL_ORIGIN_MEMBERS
email_txt = loader.get_template('account/emails/createaccount.html')
email_html = loader.get_template('account/emails/createaccounthtml.html')
email_context = Context({'u_name': username,
'username': username,
'password': password,
})
new_user_mail = EmailMultiAlternatives('Welcome!',
email_txt.render(email_context),
admin_email,
[user.email, ],
headers={'Reply-To': 'admin#admin.com'}
)
new_user_mail.attach_alternative(email_html.render(email_context), 'text/html')
new_user_mail.send()
except:
pass
return redirect('/account/thankyou/?next=%s'%next)
except:
pass
else:
print('user form in not valid')
else:
signup_form = Email_Only_SignUp_Form()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
email_only_signup_form.html
{% extends "index.html" %}
{% block heroslider %}
<div class="page_title2" style="padding:150px 0px 50px 0px;">
<div class="container">
<h1>User Registration</h1>
</div>
</div><!-- end page title -->
{% endblock %}
{% block main_body %}
<style type="text/css">
input[type='radio'], input[type='checkbox'] {
width:20px;
vertical-align: middle;
}
div.reg_error {
position:relative;
top:-10px;
margin-top:0px;
padding-top:0px;
color:red;
}
</style>
<div class="container">
<form class="pagesignup logiform" action="" method="POST">{% csrf_token %}
<div class="row">
<div class="large-12 columns" style="margin-bottom: 30px;">
<div class="reg_form">
<div class="sky-form">
<header>REGISTER</header>
</div>
<div class="row">
<div class="large-12 columns">
<p>Email<br/>
{{signup_form.email}}
<div class="reg_error">{{ signup_form.email.errors.as_text }}{{email_error}}</div></p>
</div>
</div>
<div class="row">
<div class="large-12 large-centered columns" style="text-align:center;padding:20px;">
<input class="but_medium1" style="border:none;" type = "submit" value="REGISTER" /><br>
<br>By clicking on register, you have read and agreed to our terms of use
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<!-- Google Code for Sign Up Page (landed) Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 969557266;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "5zU4CJby_FoQkoqpzgM";
var google_remarketing_only = false;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/969557266/?label=5zU4CJby_FoQkoqpzgM&guid=ON&script=0"/>
</div>
</noscript>
{% endblock %}
You have not passed the signup_form to the template.
return render_to_response(template_name, {'signup_form': signup_form}, context_instance=RequestContext(request))
I have no idea what locals() does.
Edit: I just saw locals which is a built in python function. It will be better if you explicitly pass the variables you need in the template.
Edit 2: Check if it is the correct template_name. In the template simply print and see the form {{ signup_form }}. See if it is available.
You are not returning the form.
Try changing the last line of the view to
return render_to_response(template_name, locals(), context_instance=RequestContext(request, {'signup_form' : signup_form ))

Categories

Resources