File could not be opened because it is empty - python

I want to upload 2 images from requests. I am creating the function which accepts the request.files as a parameter and save both images.
The function is :
def store_offer_images(files, **service_response):
"""
Stores the Images
"""
create_diretory_if_not_exist()
lrg_img, sml_img = files.get('detail_image'), files.get('listing_image')
lrg_img_filename = service_response.get('content').get('offerId') + ".png"
sml_img_filename = service_response.get('content').get('offerId') + ".png"
sml_img.save(
os.path.join(config.NORMAL_FILE_UPLOAD_FOLDER, sml_img_filename))
lrg_img.save(
os.path.join(config.LARGE_FILE_UPLOAD_FOLDER, lrg_img_filename))
When I am trying to save the images. It saves properly. files is the request.files and service_response is the kwargs.
When I want to open image in Finder(OS GUI Window), then I got the message:
The file “b516f2dca72e4f559c3a72a1f48727a9.png” could not be opened because it is empty.
How can I upload the images?
Edit:
When I look files in the pdb, here are the response:
(pdb) files.get('detail_image')
(pdb) <FileStorage: u'python-640x444.png' ('image/png')>
The model which models my request data is:
import datetime
from app_config import AppConfig
class Offer(object):
"""
Offer Details
"""
def __init__(self, form):
self.REST_API_TIME_FORMAT = AppConfig().REST_API_TIME_FORMAT
self.title = form.get('title')
self.start_date = form.get('startsOn') + ' 00:00'
self.end_date = form.get('endsOn') + ' 23:59'
self.short_description = form.get('shortDescription')
self.long_description = form.get('longDescription')
self.outlets = form.getlist('outlets')
self.offer_value = form.get('offerValue')
self.offer_old_value = form.get('oldValue')
self.currency = form.get('currency')
def add_offer_body(self):
"""
Return the request body in json format
"""
outlets_list = []
for i in self.outlets:
outlets_list.append({'code': i})
starts_on_date = datetime.datetime.strptime(
self.start_date, '%d/%m/%Y %H:%M')
ends_on_date = datetime.datetime.strptime(
self.end_date, '%d/%m/%Y %H:%M')
body = {
"outlets": outlets_list,
"title": self.title,
"shortDescription": self.short_description,
"longDescription": self.long_description,
"endsOn": ends_on_date.strftime(self.REST_API_TIME_FORMAT),
"startsOn": starts_on_date.strftime(self.REST_API_TIME_FORMAT),
"isActive": "true",
}
if self.offer_value is not u'':
body['offerValue'] = {
"value": self.offer_value,
"currency": self.currency
}
if self.offer_old_value is not u'':
body["offerOldValue"] = {
"value": self.offer_old_value,
"currency": self.currency
}
return body
def __repr__(self):
return self.title
The views.py is:
#portal.route('/admin/offers/add', methods=['POST'])
def add_offer():
"""
Return status of added offer
"""
offer = Offer(request.form)
if controller.valid_content(request.files):
service_response = controller.add_offer(offer)
if 'errors' in service_response:
message = str(service_response.get('errors')[0].get('message'))
flash("Adding Offer Failed.!! " + message)
current_app.logger.error(
'Offer adding failed with details' + str(request.form))
return redirect(url_for('portal.list_running_offers'))
else:
controller.store_offer_images(request.files, **service_response)
current_app.logger.info('User added a offer successfully.')
flash("Offer added successfully..!!")
return redirect(url_for('portal.list_running_offers'))
else:
flash("Please upload all Images of mentioned Resolution.!!")
return render_template(
'addoffer.jinja', body=offer.add_offer_body(), help=help_messages)
The HTML is:
{% extends "base.jinja" %}
{% block script %}
<script type="text/javascript" src="static/js/addOffer.js"></script>
<script type="text/javascript" src="static/js/bootstrap-datepicker.min.js"></script>
<link href="static/css/datepicker.css" rel="stylesheet">
{% endblock %}
{% block title %}
Add Offer
{% endblock %}
{% block content %}
<legend><h1>
Add Offer
</h1></legend>
<br>
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<form id="offerForm"enctype="multipart/form-data" class="form-horizontal" action="{{ url_for('portal.add_offer') }}" data-toggle="validator" role="form" method="post">
<div class="form-group">
<label class="control-label col-xs-3" for="file">OFFER LISTING IMAGE *</label>
<div class="col-xs-7 input-group">
<input id="image" type="file" class="form-control" name="listing_image" accept="image/x-png" data-error="{{help.listing_image}}" required>
<span class="help-block with-errors">{{help.listing_image}}</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="file">OFFER DETAIL IMAGE *</label>
<div class="col-xs-7 input-group">
<input id="image" type="file" class="form-control" name="detail_image" accept="image/x-png"
data-error="{{help.detail_image}}" required>
<span class="help-block with-errors">{{help.detail_image}}</span>
</div>
</div>
</form>
</div>
<div class="col-md-1"></div></div>
</div>
{% endblock %}

I fixed the problem. It was happening because If I perform any operation on Image, it will move my pointer at last, so when you save the image, it start saving image where your pointer is, which is at the last. So the saved image is empty.
Now to fixed this I just move my pointers to the beginning. Here is sample code what I did:
if img is not None and img.filename != u'':
img.seek(0, os.SEEK_END)
size = img.tell()
imgs = Image.open(img)
res = imgs.size
img.seek(0)

Related

Django Dependent/Chained Dropdown List - Select A Valid Choice Error

I have implemented a Dependent dropdown list within Django but when I try to submit the form I get the following error 'Select a valid choice. That choice is not one of the available choices.'
I have spent a while looking on the web for the answer and have tried a few with little avail.
From my understanding and reading, this is an error because I render the form with a queryset of none. Then I use ajax to fill in the options. Even though I have updated the dropdown list, the form validation is checking my submitted answer against a queryset of none - thus the error.
So i'm hoping someone can help me to update the choices the form will accepted on form submission.
views.py
# stage6 is where I render my view and check validation
def stage6(request):
form_deal = DealForm(request.POST or None, prefix='inst')
if form_deal.is_valid():
form_deal.save()
messages.success(request, 'Deal added successfully.')
form_deal = DealForm()
context = {
'dform': form_deal,
}
return render(request, 'stages/stage6/stage6.html', context)
# This is used for my ajax request
def load_offers(request):
property_process_id = request.GET.get('propertyprocess_link')
offers = Offer.objects.filter(propertyprocess_link=property_process_id).order_by('id')
return render(request, 'stages/stage6/offers_dropdown_list.html', {'offers': offers})
forms.py
class DealForm(forms.ModelForm):
deal_date = forms.CharField(
label='',
widget=forms.TextInput(attrs={'type': 'date'})
)
target_move_date = forms.CharField(
label='',
widget=forms.TextInput(attrs={'type': 'date'})
)
def __init__(self, *args, **kwargs):
super(DealForm, self).__init__(*args, **kwargs)
# filter the foreign keys shown
self.fields['propertyprocess_link'].queryset = PropertyProcess.objects.filter(sector="Sales")
# filter used for ajax request
self.fields['offer_accepted'].queryset = Offer.objects.none()
# add a "form-control" class to each form input
# for enabling bootstrap
for name in self.fields.keys():
self.fields[name].widget.attrs.update({
'class': 'form-control',
})
class Meta:
model = Deal
fields = ('propertyprocess_link',
'deal_date',
'price_agreed',
'target_move_date',
'offer_accepted'
)
models.py
class Deal(models.Model):
propertyprocess_link = models.ForeignKey(PropertyProcess,
on_delete=models.CASCADE)
deal_date = models.DateField()
price_agreed = models.IntegerField()
target_move_date = models.DateField()
offer_accepted = models.ForeignKey(Offer,
on_delete=models.CASCADE)
class Meta:
verbose_name_plural = "deals"
def __str__(self):
return '%s, %s' % (
self.propertyprocess_link.property_link.address_line_1,
self.propertyprocess_link.property_link.postcode
)
html
{% block content %}
<div class="container-fluid header-container">
<div class="row">
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
<div class="card-au card-signin my-5">
<div class="card-body">
<form id="offers-form" data-offers-url="{% url 'ajax_load_offers' %}" class=" text-center text-white" method="post" novalidate>
{% csrf_token %}
{{ dform.non_field_errors }}
<div class="form-colour mt-2">
{{ dform.propertyprocess_link.errors }}
<label class="mb-0 mt-1">Property Being Offered On:</label>
{{ dform.propertyprocess_link }}
</div><div class="form-colour mt-2">
{{ dform.offer_accepted.errors }}
<label class="mb-0 mt-1">Offer Being Accepted:</label>
{{ dform.offer_accepted }}
</div>
<div class="form-colour mt-2">
{{ dform.price_agreed.errors }}
<label class="mb-0 mt-1">Price Agreed:</label>
{{ dform.price_agreed }}
</div>
<div class="form-colour mt-2">
{{ dform.deal_date.errors }}
<label class="mb-0 mt-1">Deal Date:</label>
{{ dform.deal_date }}
</div>
<div class="form-colour mt-2">
{{ dform.target_move_date.errors }}
<label class="mb-0 mt-1">Target Move Date:</label>
{{ dform.target_move_date }}
</div>
<div class="mb-3"></div>
{# hidden submit button to enable [enter] key #}
<div class="hidden-btn" style="margin-left: -9999px"><input class="hidden-btn" type="submit" value=""/></div>
<div class="text-center mt-2">
<input type="submit" class="login-btn btn-green btn btn-lg border-green text-uppercase py-3" value="Add Deal" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
{% block postloadjs %}
{{ block.super }}
<script>
$("#id_inst-propertyprocess_link").change(function () {
var url = $("#offers-form").attr("data-offers-url"); // get the url of the `load_offers` view
var propertyID = $(this).val(); // get the selected Property Process ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/ajax/load-offers/)
data: {
'propertyprocess_link': propertyID // add the Property Process id to the GET parameters
},
success: function (data) { // `data` is the return of the `load-offers` view function
$("#id_inst-offer_accepted").html(data); // replace the contents of the offers input with the data that came from the server
}
});
});
</script>
{% endblock postloadjs %}
Thanks very much for any help anyone can give.

Flask - how to keep list index after form submit?

I have a list of images that I want to display on a page. These image names are formatted basically YYYYMMDD_HHMMSS.jpg. I want this single page to either list all images, or only list and show those taken on a certain date (meaning a main page, not like /index to show all images, /date-specific to show some images).
So far, I have been able to show all images, and click "next"/"previous" buttons to loop through all images. I also have a table below the image, showing all the images that are in the index.
Works great - no issues.
However, I am also trying to implement a date filter, where the user can select a date from the Calendar Picker, and have the site filter out and only show photos on that day. So far, I can successfully filter one time. However, when I click "next"/"previous" buttons, or choose an image from the table, it resets back to the full list of images.
How do I keep the filtered list? I thought I could do it by keeping the date chosen in the Input field, but after using the "next"/"previous" buttons, the whole page resets and it clears that field.
I also tried including the list in the HTML portion, but it still returns all the photos. (Also makes the URL ugly, since it includes the image list for each photo listed in the table):
<td> {{ image }} </td>
Here's a .gif of the page I'm working on.. First, you'll see I can successfully click around, navigate between all photos. Then, I can successfully filter to show photos on a specific date. However, anything past that keeps sending me back to the full image list.
Anyways, without further ado, here's the codes. (Note I try to keep it minimal, so might have omitted an important piece, so please let me know if I need to post something else here):
routes.py
import os
import random
from flask import render_template, url_for, request, Blueprint, redirect # noqa
from app import app
IMAGE_FOLDER = r"C:/MyPath/Test"
FAVORITE_LIST = os.path.join(IMAGE_FOLDER, "favorites.txt")
blueprint = Blueprint('images', __name__,
static_url_path='/static/images',
static_folder=IMAGE_FOLDER)
app.register_blueprint(blueprint)
images = os.listdir(IMAGE_FOLDER)
image_urls = ["20190411_123200.jpg", ... other images in a list]
class Photo_Index():
def __init__(self, index=0):
self.index = index
def increase_number(self, num_images):
if self.index == num_images:
self.index = 0
else:
self.index = self.index + 1
return self.index
def decrease_number(self, num_images):
if self.index == 0:
self.index = num_images
else:
self.index = self.index - 1
return self.index
def random_number(self, num_images):
self.index = random.randint(0, num_images)
return self.index
def set_number(self, number):
self.index = number
return self.index
# functions to create and edit Favorites. this works so I'm excluding]
def day_month_year(filename):
"""
Takes a string `20190212` and pulls out Year, Month, Date
"""
year = filename[:4]
month = filename[4:6]
day = filename[6:8]
return str(year + "-" + month + "-" + day)
def get_files_on(specific_date):
_files = []
print("\nLooking for files on:", specific_date, "\n")
for file in image_urls:
# print(file, day_month_year(file))
if day_month_year(file) == specific_date:
_files.append(file)
return _files
photo_index_obj = Photo_Index()
fav_photo_index = Photo_Index()
def update_index(rqst, indx_obj, num_images):
print("Updating index, have", num_images, "photos")
if num_images == 1:
indx_obj.set_number(0)
elif 'prev-photo' in rqst.form:
indx_obj.decrease_number(num_images)
elif 'next-photo' in rqst.form:
indx_obj.increase_number(num_images)
elif 'random-photo' in rqst.form:
indx_obj.random_number(num_images)
return indx_obj
#app.route("/<chosen_image>", methods=["GET", "POST"])
#app.route("/", methods=["GET", "POST"])
def default_template(date=None, image_list=None, chosen_image=None):
if image_list is None:
image_list = image_urls
num_images = len(image_list) - 1
if request.method == "POST":
if 'go-to-date' in request.form:
date = request.form['go-to-date']
image_list = get_files_on(date)
num_images = len(image_list) - 1
photo_index_obj.set_number(0)
if len(image_list) == 0:
image_list = ["no_images_for_date.jpg"]
elif 'prev-next-buttons' in request.form:
print("Updating index, have", num_images, "photos")
update_index(request, photo_index_obj, num_images)
elif 'favorite-photo' in request.form:
add_to_favorites(image_list[photo_index_obj.index])
elif 'un-favorite-photo' in request.form:
remove_from_favorites(image_list[photo_index_obj.index])
if chosen_image is None:
chosen_image = image_list[photo_index_obj.index]
elif chosen_image is not None:
photo_index_obj.set_number(image_list.index(chosen_image))
favorite = is_favorite(image_list[photo_index_obj.index])
print("Images:", image_list)
return render_template('index.html',
title="Local Image Viewer",
photo_index=photo_index_obj.index,
image=chosen_image,
image_list=image_list,
favorite=favorite)
#app.route("/<chosen_image>", methods=["GET", "POST"])
def chosen_image(chosen_image):
date = request.form['go-to-date']
return default_template(date=date,
chosen_image=chosen_image)
index.html (I omitted the Select list, as that's kind of superfluous for this post)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ title }}</title>
<link rel="stylesheet" type="text/css" href= "{{ url_for('static',filename='styles/index.css') }}">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
{% extends "layout.html" %}
{% block content %}
<h3>Index: {{ photo_index }}</h3>
<h3>Filename: {{ image }}</h3>
<div id="calendar-selector">
{% include "/HTML Snippets/calendar.html" %}
</div>
<div class='image-container' id='image'>
{% include "/HTML Snippets/favorite_button.html" %}
<img src="{{ url_for('images.static', filename=image) }} " id="the-photo">
</div>
<div class='button-container' id='buttons'>
<form action="" method="post">
<input type="hidden" name="prev-next-buttons">
<input type="submit" value="Prev photo" name='prev-photo'>
<input type="submit" value="Next photo" name='next-photo'>
<input type="submit" value="Random photo" name='random-photo'>
<br/>
<button type='button' id='rotate-button' onclick="rotateMeCounterClockwise('#the-photo')">Rotate Photo CounterClockwise</button>
<button type='button' id='rotate-button' onclick="rotateMeClockwise('#the-photo')">Rotate Photo Clockwise</button>
</form>
</div>
<div class='table-container'>
<table id='image-list' name='select-from-table'>
{% for image_row in image_list | batch(3) %}
<tr>
{% for image in image_row %}
<td> {{ image }} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
</body>
</html>
and the calendar bit, calendar.html
{% block topscripts %}
<link rel="stylesheet" type="text/css" href= "{{ url_for('static',filename='styles/calendar.css') }}">
<script>
$(function() {
$("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
});
</script>
{% endblock %}
{% block content %}
<form method="post" action="{{ url_for('default_template') }}">
<input type="hidden" name="calendar-form">
<p>
Date: <input type="text" id="datepicker" name='go-to-date'
{% if request.form['go-to-date'] is not none %}
value="{{request.form['go-to-date']}}"
{% endif %}
></p>
<input type="submit">
</form>
{% endblock %}
{% block endscripts %}
{% endblock %}
You need to pass along enough information in your next/previous form and in the table links to re-apply the date filter. Your calendar form is separate from the next/previous navigation form, the browser won't serialise information from one when submitting the other. Clicks on <a href="..."> links will not include the date input field value either.
Note that clicks on the table links generate GET requests, so you need to look for go-to-date in the request.values mapping to accommodate both query parameters and form data.
You need to look for this parameter not only when you receive a POST request, but for all requests:
if 'go-to-date' in request.values:
date = request.values['go-to-date']
image_list = get_files_on(date)
photo_index_obj.set_number(0)
if len(image_list) == 0:
image_list = ["no_images_for_date.jpg"]
else:
image_list = image_list or image_urls
num_images = len(image_list) - 1
if request.method == 'POST':
# ...
Then generate URLs that include the parameter:
{%- set url_params = {'go-to-date': request.values['go-to-date']} if request.values['go-to-date'] else {} -%}
{% for image in image_row %}
<td> {{ image }} </td>
{% endfor %}
For the next/previous form, just add a hidden input field with the current go-to-date value:
<form action="" method="post">
<input type="hidden" name="prev-next-buttons">
{%- if request.values['go-to-date'] -%}
<input type="hidden" name="go-to-date" value="{{ request.values['go-to-date'] }}">
{%- endif -%}
<input type="submit" value="Prev photo" name='prev-photo'>
<input type="submit" value="Next photo" name='next-photo'>
<input type="submit" value="Random photo" name='random-photo'>
<br/>
<button type='button' id='rotate-button' onclick="rotateMeCounterClockwise('#the-photo')">Rotate Photo CounterClockwise</button>
<button type='button' id='rotate-button' onclick="rotateMeClockwise('#the-photo')">Rotate Photo Clockwise</button>
</form>

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 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 ))

Ajax avatar preview with jQuery In django

I've been trying to follow a tutorial. But it doesn't want to work for me. I'm trying to get a simple (or so I thought) avatar preview shown. The problem is that it won't load, or accept the avatar. If I could get another set of eyes on this, and maybe tell me what I'm doing wrong; I'd be very appreciative.
The template: (The form is a large overall user information form)
<form class="inline" enctype="multipart/form-data" method="POST" action="/profile/edit/{{ role }}/" id="avatarLoadForm">
<input type="hidden" name="next" value="/account/settings/">
{% csrf_token %}
{% if user_info_form.errors %}{{ user_info_form.errors }}{% endif %}
<div>
<label class="form-label" for="id_avatar">Your Picture</label>
<div id="preview" class="inline-block img-frame thick">
<img src="{% if profile.avatar %}{% thumbnail profile.avatar 120x120 crop %}{% else %}{{ DEFAULT_AVATAR }}{% endif %}" id="thumb" alt="" alt="sample-pic" />
</div>
{{ user_info_form.avatar }}
</div>
<div id="edit-name">
<label class="form-label" for="id_first_name">Name</label>
{{ user_info_form.first_name }}
{{ user_info_form.last_name }}
... And so on (other info not relevant)...
The js:
(function() {
var thumb = $('img#thumb');
new AjaxUpload('imageUpload', {
action: $('#avatarLoadForm').attr('action'),
name: 'avatar',
onSubmit: function(file, extension) {
$("#preview").html('<img id="loader" src="{{ STATIC_URL }}images/ajax-loader.gif" alt="Uploading...."/>');
},
onComplete: function(file, response) {
thumb.load(function(){
$("#preview").html('');
thumb.unbind();
});
thumb.attr('src', response);
}
});
Views.py
#login_required
def edit_profile(request, profile_type):
if profile_type == 'investor':
profile = InvestorProfile.objects.get(user=request.user)
elif profile_type == 'manager':
profile = ManagerProfile.objects.get(user=request.user)
context = base_context(request)
if request.method == 'POST':
notify = "You have successfully updated your profile."
user_info_form = UserInfoForm(request.POST, request.FILES)
if user_info_form.is_valid():
user_info_form.save(request.user, profile_type)
response = simplejson.dumps({"status": "Upload Success"})
return HttpResponse (response, mimetype='application/json')
else:
initial = {}
initial['first_name'] = request.user.first_name
initial['last_name'] = request.user.last_name
initial['email'] = request.user.email
initial['about'] = profile.about
initial['country'] = profile.country
initial['about'] = profile.about
user_info_form = UserInfoForm(initial=initial)
context['user_info_form'] = user_info_form
context['profile_type'] = profile_type
context['profile'] = profile
return render_to_response('settings/base.html', context, context_instance=RequestContext(request))
Edit: Forms.py:
class UserInfoForm(forms.Form):
first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'input-text'}), max_length=30)
last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'input-text'}), max_length=30)
email = forms.EmailField(widget=forms.TextInput(attrs={'class':'input-text'}))
about = forms.CharField(widget=forms.Textarea(attrs={'class':'input-text'}), required=False)
country = forms.CharField(max_length=50, widget=forms.Select(choices=countries.COUNTRIES))
avatar = forms.ImageField(required=False)
#avatar = forms.ImageField(widget=forms.ClearableFileInput(attrs={'id':'imageUpload'}),required=False)
investor_type = forms.CharField(max_length=4, widget=forms.Select(choices=choices), required=False)
For future reference you should define Avatar as a model with its own fields regardless if it will be a thumbnail. But have you tried
<img src="{% if profile.user %}{% thumbnail avatar 120x120 crop %}{% else %}{{ DEFAULT_AVATAR }}{% endif %}" id="thumb" alt="" alt="sample-pic" />

Categories

Resources