Django form ajax submit concurrently - ajax

I have some field created by Django form and there are some other data I want to post to other form using jQuery(Ajax).
Is there any way to post them to different tables with two different ways at the same time?
form.py
class MyForm(forms.ModelForm):
class Meta:
model = models.Planning
fields = ['title','description','open','owner','upload_time']
template
<form id="myform" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.management_form }}
<div id="select_country">
<p style="display: inline;">country</p>
<select id="city">
<option selected disabled hidden>please choose</option>
{% for x in areas %}
<option value="{{x.area_country}}">{{x.area_country}}</option>
{% endfor %}
</select>
<select id="areas" name="my_areas"></select>
<br>
<div class="my_detail">
</div>
<br>
</div>
<div id="content_loi" class="col-lg-4">
<div class="col-lg-12" id="list"></div>
<div class="col-lg-12"">
<label>title:{{form.title}}</label>
<p><b>description:</b>{{form.description}}</p>
<button type="submit" class="btn btn-default" style="margin:0 auto;">submit</button>
</div>
</div>
</form>
I want to store the chosen areas and foreign key to another table with ajax
view
def make_list(request):
template = get_template('index.html')
areas = models.Area.objects.values('area_country').distinct()
max_my_id = models.RoutePlanning.objects.all().aggregate(Max('my_id'))
my_id = int(max_my_id['my_id__max']) + 1
#city = request.POST.get('my_areas')
if request.method == 'POST':
form = forms.MyForm(request.POST,initial={'owner':username,'route_id':my_id,'route_upload_time':datetime.now()})
if form.is_valid():
form.save()
return HttpResponseRedirect('/make_player')
else:
loi_form = forms.MyForm(initial={'owner':username,'route_id':my_id,'route_upload_time':datetime.now()})
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)

Related

How to change css_class for all <div> rows in Crispy form

I am using Crispy forms to render my Django form. It works smoothly but I struggle with updating the css_class for my rows. Any suggestions how to solve this? The form is retrieved from the forms.models, so ideally I do not have to update my layout for every row individually.
The documentation https://django-crispy-forms.readthedocs.io/en/latest/layouts.html#overriding-layout-objects-templates did not provide an answer to my question (or I did not understand it)
Current output in html
<div id="div_id_voornaam" class="form-group row"> </div>
Ideally: change css class for every row:
<div id="div_id_voornaam" class="row mb-3"> </div>
Forms setting
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-8'
Template setting
<div class="card-body">
<form method="post">
{% load crispy_forms_tags %}
{% csrf_token %}
{% crispy form %}
<button type="submit" value="Submit" class="btn btn-primary">Submit</button>
</form>
You need to use wrapper_css atribute. Like this:
...self.helper.layout = Layout(Field('voornaam', wrapper_class="row mb-3"))
You can check crispy documentation here: https://django-crispy-forms.readthedocs.io/en/latest/layouts.html

form.validate_on_submit(): and {{ form.csrf_token }} not working in a view.html with two forms

In http://127.0.0.1:5000/:
If defaults are "0", message in each field: "This field is required".
There are the message "csrf_token CSRF Token" above "compute0" and "compute1".
Only compute0 works.
click on compute0 shows the resulted.
click on compute1 showns nothing.
form and form1 have 3 inputs.
compute0 and compute1 call (math.sin(r))* t + u.
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import TextField, BooleanField, PasswordField, TextAreaField, validators
from compute import compute
from model import InputForm, InputForm1
app = Flask(__name__)
app.config['SECRET_KEY'] = 'Thisisasecret'
#app.route('/', methods=['GET', 'POST'])
def index():
form = InputForm(request.form)
form1 = InputForm1(request.form)
if form.validate_on_submit():
if request.method == 'POST':
r = form.r.data
t = form.t.data
u = form.u.data
s = compute(r,t,u)
else:
s = None
return render_template("view.html", form=form, form1=form1, s=s)
if form1.validate_on_submit():
if request.method == 'POST':
r1 = form1.r1.data
t1 = form1.t1.data
u1 = form1.u1.data
s1 = compute(r1,t1,u1)
else:
s1 = None
return render_template("view.html", form=form, form1=form1, s1=s1)
return render_template("view.html",form=form, form1=form1)
if __name__ == '__main__':
app.run(debug=True)
from flask_wtf import FlaskForm
from wtforms import validators, StringField, PasswordField,FloatField, validators
class InputForm(FlaskForm):
r = FloatField(label='var_r',default=0,validators=[validators.DataRequired()])
t = FloatField(label='var_t',default=0,validators=[validators.DataRequired()])
u = FloatField(label='var_u',default=0,validators=[validators.DataRequired()])
class InputForm1(FlaskForm):
r1 = FloatField(label='var_r1',default=0,validators=[validators.DataRequired()])
t1 = FloatField(label='var_t1',default=0,validators=[validators.DataRequired()])
u1 = FloatField(label='var_u1',default=0,validators=[validators.DataRequired()])
import math
def compute(r,t,u):
return (math.sin(r))* t + u
<form method="post" action="">
{{ form.csrf_token }}
{% for field in form %}
<dt>{{ field.name }}
<dd>{{ field|safe }} {{field.label }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}</ul>
{% endif %}</dd>
{% endfor %}
<p><input type=submit value=Compute0></form></p>
<h5> Valor: </h5>
<p>
{% if s != None %}
{{ s }}
{% endif %}
</p>
<form method="post" action="">
{{ form.csrf_token }}
{% for field in form1 %}
<dt>{{ field.name }}
<dd>{{ field|safe }} {{field.label }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}</ul>
{% endif %}</dd>
{% endfor %}
<p><input type=submit value=Compute1></form></p>
<h5> Valor: </h5>
<p>
{% if s1 != None %}
{{ s1 }}
{% endif %}
</p>
if i understand your description, you have 2 independent forms on the same page that both send POST requests to the same view function to process.
you want to update the placeholder below of each form depending on which form is already submitted, here i think you need to perform an ajax call since (based on your code above) there's no way to keep or persist the data of the other form (database for e.g)
so to do:
update the code of the Form InputForm
since the 2 forms have the same fields you need just one for this use case and then adapt and extend the logic for other forms with different set of fields
from flask_wtf import FlaskForm
from wtforms.fields import FloatField, SubmitField
from wtforms.validators import DataRequired
class InputForm(FlaskForm):
r = FloatField('r', validators=[DataRequired()])
t = FloatField('t', validators=[DataRequired()])
u = FloatField('u', validators=[DataRequired()])
submit = SubmitField('Submit')
update the template
<!-- the first form -->
<form class="form" id="form-1" method="POST" novalidate>
{{ form_1.csrf_token }}
<div class="row">
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_1.r.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_1.r(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_1.t.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_1.t(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_1.u.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_1.u(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
</div>
<div class="form-group row d-flex justify-content-between border bg-light p-3">
{{ form_1.submit(class="btn btn-sm btn-primary rounded-0 shadow-none") }}
<span class="placeholder">sin(r) * t + u = 0.00</span>
</div>
</form>
<!-- the second form -->
<form class="form" id="form-2" method="POST" novalidate>
{{ form_2.csrf_token }}
<div class="row">
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_2.r.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_2.r(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_2.t.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_2.t(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_2.u.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_2.u(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
</div>
<div class="form-group row d-flex justify-content-between border bg-light p-3">
{{ form_2.submit(class="btn btn-sm btn-primary rounded-0 shadow-none") }}
<span class="placeholder">sin(r) * t + u = 0.00</span>
</div>
</form>
in your view function (here i just i isolated the logic in Blueprint #bp):
from flask import Blueprint, render_template, request, jsonify
from .forms import InputForm
from .utils import compute
bp = Blueprint(
'home',
__name__,
static_folder='static',
static_url_path='/home/static',
template_folder='templates',
# url_prefix=None,
# subdomain=None,
# url_defaults=None,
# root_path=None,
# cli_group=<object object>
)
#bp.route('/', methods=['GET', 'POST'])
def index():
form_1 = InputForm()
form_2 = InputForm()
if request.method == 'POST':
# we handle the "POST" request of the submitted "form_1"
if form_1.validate_on_submit():
r = form_1.r.data
t = form_1.t.data
u = form_1.u.data
s = compute(r,t,u)
return jsonify(s=s if s else 0, errors={})
else:
return jsonify(s=0, errors=form_1.errors)
# we handle the "POST" request of the submitted "form_2"
if form_2.validate_on_submit():
r = form_2.r.data
t = form_2.t.data
u = form_2.u.data
s = compute(r,t,u)
return jsonify(s=s if s else 0, errors={})
else:
return jsonify(errors=form_2.errors)
return render_template("home/index.html", form_1=form_1, form_2=form_2)
the ajax part:
i suggest you my answer on how to take advantage of jinja2 template inheritance to insert locally a js (the same with css) blocks for particular page.
base on, i assume your are using jquery and since we want jinja2 to render this javascript line url: "{{ url_for('home.index') }}", so in your template add this code
$(document).ready(function() {
"use strict";
$('.form').submit(function(e) {
e.preventDefault();
// get the id of the form currently submitted
let id = $(this).attr('id');
$.ajax({
url: "{{ url_for('home.index') }}",
type: 'POST',
cache: false,
dataType: 'json',
data: $('#' + id).serialize(), // serialize the form
success: function(data) {
// console.log(data);
// sanitize the form before processing the submitted fields
if( ! data.errors.hasOwnProperty('r')){
$('#' + id + ' input[name=r]').removeClass('is-invalid').next(".invalid-feedback").text('');
}
if( ! data.errors.hasOwnProperty('t')){
$('#' + id + ' input[name=t]').removeClass('is-invalid').next(".invalid-feedback").text('');
}
if( ! data.errors.hasOwnProperty('u')){
$('#' + id + ' input[name=u]').removeClass('is-invalid').next(".invalid-feedback").text('');
}
// #see https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
if( ! jQuery.isEmptyObject(data.errors)) { // Errors (data.errors = {})
console.log('Errors');
if(data.errors.hasOwnProperty('r')){
$('#' + id + ' input[name=r]').addClass('is-invalid').next(".invalid-feedback").text(data.errors['r']);
}
if(data.errors.hasOwnProperty('t')){
$('#' + id + ' input[name=t]').addClass('is-invalid').next(".invalid-feedback").text(data.errors['t']);
}
if(data.errors.hasOwnProperty('u')){
$('#' + id + ' input[name=u]').addClass('is-invalid').next(".invalid-feedback").text(data.errors['u']);
}
// update placeholder with the returned value
$('#' + id + ' .placeholder').html('sin(r) * t + u = ' + data.s);
} else { // Passed
console.log('Passed');
// get the submitted fields
let r = $('#' + id + ' input[name=r]').val();
let t = $('#' + id + ' input[name=t]').val();
let u = $('#' + id + ' input[name=u]').val();
// update placeholder with the returned value
$('#' + id + ' .placeholder').html('sin(' + r + ') * ' + t + ' + ' + u + ' = ' + data.s);
// reset fields
$('#' + id + ' input[name=r]').val('');
$('#' + id + ' input[name=t]').val('');
$('#' + id + ' input[name=u]').val('');
}
}
});
});
});
and finally this a
hope this solves your issue.

Userfrosting - Get Working, Post blank screen with no error in log

I'm creating my first Userfrosting app and trying a few simple things but falling at the first hurdle. I am trying to create a form which adds bands to a database table:
CREATE TABLE `uf_band` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`band_name` text NOT NULL,
`band_description` longtext NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`modified_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
initialize.php:
$table_band = new \UserFrosting\DatabaseTable($app->config('db')['db_prefix'] . "band", [
"band_name",
"band_description",
"created_at",
"modified_at"
]);
index.php for the routes:
$app->get('/bands/new/?', function () use ($app) {
$controller = new UF\BandController($app);
return $controller->newBand();
});
The New Band form using GET works fine.
BandController.php
public function newBand(){
if (!$this->_app->user->checkAccess('uri_bands')){
$this->_app->notFound();
}
$this->_app->render('bands/new.twig', []);
}
and if I add this to the newBand Controller to test, it writes to the database when I load the new band form, which is fine:
$new_band = new Band([
"band_name" => "band_name",
"band_description" => "band_description"
]);
$new_band->save();
$id = $new_band->id;
The problem is the Save using Post. Even if I hard code in the values and do not even try to read the POST data, all I get is a blank screen. There are no error messages and nothing in the apache error.log:
index.php
$app->post('/bands/new/?', function () use ($app) {
$controller = new UF\BandController($app);
return $controller->saveBand();
});
BandController.php
public function saveBand(){
$new_band = new Band([
"band_name" => "band_name",
"band_description" => "band_description"
]);
$new_band->save();
$id = $new_band->id;
}
If I replace my POST route with
$app->post('/bands/new/?', function () use ($app) {
echo 'post';
})
I still just get a blank screen.
Here's bands/new.twig though I think the problem is before this:
{% extends "layouts/layout-dashboard.twig" %}
{% set page_group = "dashboard" %}
{% block page %}
{% set page = page | merge({
"title" : "Add New Band",
"description" : ""
}) %}
{{ parent() }}
{% endblock %}
{% block content %}
<h1>{{page.title}}</h1>
<p>{{page.description}}</p>
<div class="row">
<div class="col-lg-6">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-users"></i>Add New Band</h3>
</div>
<div class="panel-body">
<form class="form-horizontal" role="form" name="bands" action="{{site.uri.public}}/bands/new" method="post">
<div class="form-group">
<label for="input_band" class="col-sm-4 control-label">Band Name</label>
<div class="col-sm-8">
<input type="text" id="input_title" class="form-control" name="band_name" placeholder="Please enter the band name">
<!--<p class="help-block">Enter the band name here</p>-->
</div>
</div>
<div class="form-group">
<label for="input_title" class="col-sm-4 control-label">Description</label>
<div class="col-sm-8">
<textarea type="text" id="input_title" class="form-control" name="band_description" placeholder="Please enter a description of the band. This may be displayed publically"></textarea>
<!--<p class="help-block">This will become the new title for all users in the selected group.</p> -->
</div>
</div>
<div class="form-group">
<label for="input_group" class="col-sm-4 control-label">Genre</label>
<div class="col-sm-8">
<select id="input_group" class="form-control select2" name="genre_id">
{% for group in groups %}
<option value="{{group.id}}">{{group.name}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success text-center">Add Band</button>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block page_scripts %}
<script>
$(document).ready(function() {
// Load the validator rules for this form
var validators = {{validators | raw}};
ufFormSubmit(
$("form[name='add_band']"),
validators,
$("#userfrosting-alerts"),
function(data, statusText, jqXHR) {
// Reload the page on success
window.location.reload(true);
}
);
});
</script>
{% endblock %}
Thanks for any thoughts. With no error messages, this is driving me nuts!
Seems like you have forgotten the csrf token.
You can add this hidden input field:
<input type="hidden" name="{{csrf_key}}" value="{{csrf_token}}">
and read more here.

AJAX handler not called

Trying to create a component under October CMS which create a ToDo list (Look at this video). Adding an item works fine but now I'm trying to set up and Ajax handler to delete one element when a button is clicked.
Thi is the html code:
<form>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Tasks assigned to: {{ __SELF__.name }}</h3>
</div>
<div class="panel-body">
<div class="input-group">
<input name="task" type="text" id="inputItem" class="form-control" value="" \>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary"
data-request="{{ __SELF__ }}::onAddItem"
data-request-success="$('#inputItem').val('')"
data-request-update="'{{ __SELF__ }}::tasks': '#result'"
>Add</button>
</span>
</div>
<ul class="list-group" id="result">
{% partial __SELF__ ~ '::tasks' tasks=__SELF__.tasks removeId=__SELF__.removeId %}
</ul>
</div>
</div>
<form>
and the code of the component (named tasks) that render the list of tasks:
{% if tasks|length > 0 %}
{% for i in 0..tasks|length-1 %}
<li class="list-group-item">
{{ tasks[i] }}
<button class="close pull-right"
data request="{{ __SELF__ }}::onRemoveItem"
data-request-success="console.log(data)"
>
×
</button>
</li>
{% endfor %}
{% endif %}
Lastly the code of the handler (don't do so much):
public function onRemoveItem()
{
return [
'Name' => 'Federico';
];
}
Now, I set up the handler onRemoveItem putting its data-request in a button and, as explained on this page, clicking the button should start the handler's execution but this don't happen, while all works correctly in the Add button that insert the tasks in the database.
Can someone explain me what I'm doing wrong?
(In case someone want to see the page the link is http://afterlife.ddns.net/
EDIT:
Solved, I had to link the framework js in the layout file

Issues with uploading images to a carousel [duplicate]

This question already has an answer here:
Django template/view issues with carousel
(1 answer)
Closed 7 years ago.
OK, so here's the deal:
This is currently what I'm working on:
See the two arrows at the top? That's where a carousel of pictures should be. However, there are no pictures in this carousel. That is, until I click the 'Upload' Button.
So, my goal is to make the pictures appear on the first page before I even click the 'upload' button.
How can I fix this problem? I'm kind of a noob at Django, and writing this code is like pulling teeth.
My code:
Index.html
{% extends 'webportal/defaults.html' %}
{% block body %}
{% include 'webportal/carousel.html' %}
<br/>
<div class="container">
<div class="row">
<div class="col-md-12">
<p> So far we have been able to establish what the user tables will be have created or are in process of
creating
the ability to create, update, destroy users.</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p> For now this ability is limited to the main user table, however the models will be easily extended
to other
tables as they are needed</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p> Also not a lot of thought has gone into styling yet, we know that the page is suppose to resemble
the parent
organizations page. Right now we have been more focused on getting each individual component
working. Later we
will merge them into a whole. </p>
</div>
</div>
</div>
{% include 'webportal/info_row.html' with one=one two=two three=three %}
{% endblock %}
Carousel.html:
{% load staticfiles %}
{% load filename %}
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
{% for document in documents %}
<div class="item {% if forloop.first %} active {% endif %}">
<div class="row">
<div class="col">
<li>{{document.docfile.name}}</li>
<img src = "{{STATIC_URL}}img/{{document|filename}}" >
<p align="center"><form style="text-align:center" action="{% url 'webportal:delete' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.Document.label_tag }} {{ form.Document.help_text }}</p>
<p>
{{ form.Document.errors }}
{{ form.Document.docfile }}
</p>
<p><input type="submit" value="Delete" /></p>
</form></p>
</div>
</div>
</div>
{% endfor %}
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
<!-- /.carousel -->
</div>
</div>
<form action="{% url 'webportal:carousel' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</div>
Views.py:
from django.shortcuts import render
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login
from webportal.views.authentication import LoginForm
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.conf import settings
from webportal.forms.forms import DocumentForm
from webportal.models import Document, DeleteForm
is_server = True
def delete(request, my_id):
Deleted=get_object_or_404(Document, docfile=my_id)
if request.method=='POST':
form=DeleteForm(request.POST, instance=Deleted)
if form.is_valid():
Deleted.delete()
return HttpResponseRedirect('http://127.0.0.1:8000/alzheimers/')
else:
form=DeleteForm(instance=Deleted)
return render_to_response(
'webportal/index.html',
{'documents': documents, 'form': form,},
context_instance=RequestContext(request)
)
# Redirect to the document list after POST
def carousel(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect('http://127.0.0.1:8000/alzheimers/')
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
#documents=DocumentForm().
# Render list page with the documents and the form
return render_to_response(
'webportal/index.html',
{'documents': documents, 'form': form,},
context_instance=RequestContext(request)
)
Models.py:
class Document(models.Model):
docfile = models.ImageField(upload_to='webportal/static/img/')
class DeleteForm(ModelForm):
class Meta:
model=Document
fields=[]
Forms.py:
class DocumentForm(forms.Form):
docfile = forms.ImageField(label='Select a file', help_text='max. 42 megabytes')
URls.py:
from django.conf.urls import patterns, url
from webportal.views import views, register, authentication, welcome, search, profile, event, csv_export, role_creation, \
edit_event, reports, accounts
urlpatterns = patterns('',
url(r'^reports', reports.report_page),
url(r'^search/criteria', search.get_criteria),
url(r'^search', search.search_page),
url(r'^register', register.SignUpView.as_view(), name="register"),
url(r'^login', authentication.login_view, name="login"),
url(r'^carousel', views.carousel, name="carousel"),
url(r'^delete', views.delete, name="delete"),
url(r'^profile', profile.ProfileView.as_view(), name="profile"),
url(r'^welcome', welcome.WelcomeView.as_view(), name="welcome"),
url(r'^event/creation', event.Creation.as_view(), name="event_creation"),
# url(r'^role_creation', role_creation.Creation.as_view(), name="role_creation"),
url(r'^csv_export', csv_export.CSVExport.as_view(), name="csv_export"),
url(r'^csv_import', reports.upload_file, name="csv_import"),
url(r'^logout$', 'django.contrib.auth.views.logout', {'next_page': '/alzheimers/'}),
url(r'^edit_event', edit_event.EditView.as_view(), name='edit_event'),
url(r'^parse_ajax', profile.parse_ajax),
url(r'^event/role_ajax', role_creation.ajax),
url(r'^event/all', event.view_all),
url(r'^event/information', event.ajax),
url(r'^accounts/personal', accounts.personal),
url(r'^accounts/create', accounts.create),
url(r'^accounts/edit', accounts.edit),
url(r'^accounts/remove', accounts.remove),
url(r'^$', views.bootstrap),
)
If there is a way to do this, does it involve ajax? I asked this again because of a lack of an adequate answer.
You should pass the documents context variable to the template in the view which handles the /alzheimers/ page.
UPDATE: The view you should change is the views.boostrap(). So rendering of the template will be something like this:
def bootstrap(request):
...
return render_to_response('webportal/bootstrap.html',
{'documents': Document.objects.all()},
context_instance=RequestContext(request)
)

Resources