Issues with uploading images to a carousel [duplicate] - ajax

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

Related

How to get next pages in load more django

I get data using ajax with button load more, and if it's not have next pages, it will render "all data has been displayed"
index.html
<div class="panel-body">
<div id="display-data">
<span id="loading-help">Loading data. . .</span>
</div>
</div>
<script>
var page = 1
$(document).ready(function(){
$.get("{% url 'account:profile' %}?param=get_data&page="+page,
function(data){
$("#display-data").append(data)
$("#loading-help").remove()
page++
})
</script>
data-ajax.html
{% for data in datas %}
<div class="list-trx-data">
<div class="row align-items-center">
<div class="col-md-8">
<div class="row align-items-center">
<div class="col-md-4 col-sm-12 col-12 data-date">
{{data.get_formatted_date}}</div>
<div class="col-md-8 col-sm-12 col-12 data-name">
{{data.get_data}}</div>
</div>
</div>
<div class="col-md-4">
<div class="row align-items-center">
<div class="col-md-6 col-8 data-amount">
{{data.get_formatted_amount}}</div>
<div class="col-md-6 col-4 ">
<div class="data-progress">
<div class="pg-bar" style="width:
{{data.get_data.get_progress_str}}"></div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% if datas.has_other_pages %}
{% if datas.has_next %}
<a href="javascript:void(0)" class="btn btn-ghost btn-block mt-2"
id="load-more-btn">Load More</a>
{% else %}
<a href="javascript:void(0)" class="btn btn-ghost btn-block mt-2"
id="load-more-btn">All data has been displayed</a>
{% endif %}
{% endif %}
<script>
$("#load-more-btn").click(function(){
$.get("{% url 'account:profile' %}?param=get_data&page="+page,
function(data){
$("#display-data").append(data)
page++
})
})
</script>
I have try it but it's render all button
before click load more
after click load more
how to fix it ?
Firstly, don't place javascript in the data-ajax.html. All the javascript code should be placed in index.html, where all the logics need to be implemented. If there is not other data, data-ajax.html returned should be empty.
data-ajax.html
{% for data in datas %}
<div class="list-trx-data">
<div class="row align-items-center">
<div class="col-md-8">
<div class="row align-items-center">
<div class="col-md-4 col-sm-12 col-12 data-date">
{{data.get_formatted_date}}</div>
<div class="col-md-8 col-sm-12 col-12 data-name">
{{data.get_data}}</div>
</div>
</div>
<div class="col-md-4">
<div class="row align-items-center">
<div class="col-md-6 col-8 data-amount">
{{data.get_formatted_amount}}</div>
<div class="col-md-6 col-4 ">
<div class="data-progress">
<div class="pg-bar" style="width:
{{data.get_data.get_progress_str}}"></div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% if datas.has_other_pages %}
{% if datas.has_next %}
<a href="javascript:void(0)" class="btn btn-ghost btn-block mt-2"
id="load-more-btn">Load More</a>
{% endif %}
In your index.html, check if ajax call returned anything, if not, then change button text, else, remove the button element, since your data-ajax.html already has button based on {% if datas.has_other_pages %}.
index.html
<div class="panel-body">
<div id="display-data">
<span id="loading-help">Loading data. . .</span>
</div>
</div>
<script>
$(document).ready(function(){
var page = 1; //page defined in $(document).ready()
function getData(){
$.get("{% url 'account:profile' %}?param=get_data&page="+page, function(data){
$("#loading-help").remove();
if (data){
// data was received
$("#loading-help").remove();
$("#load-more-btn").remove(); # remove the load button if data is there.
$("#display-data").append(data);
page++;
} else {
$("#load-more-btn").text("All data has been displayed"); # else, change button text.
}
});
}
getData(); //Load data for the first time.
$("#load-more-btn").click(function(){
getData(); //Load data on button click.
});
</script>

Django form ajax submit concurrently

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)

Get template block contents and call from ajax

I'm using django 1.9 and python 3. My english also isn't the best, so excuse the question if it is formulated bad.
I'm working on making my website a single-page application. I need to get the {% block %} contents of a given template, and then send that as a HttpResponse so that ajax can pick it up and inject it into the page.
I've tried using the answer from this question: Django - how to get the contents of a {% block %} tag from a template
But upon trying to fetch the contents of a block in my view like so:
response_data[content] = get_block_source('profile/login.html', 'content')
if request.is_ajax():
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
I just get this error from django, no matter what I do:
ValueError at /login/ Template block content not found
The contents of the block don't even make it to the ajax call, what gives?
EDIT:
I'll include my "content" block here:
in my template:
{% extends 'base.html' %}
{% block content %}
<div class="big-title text">Log in</div>
<div class="form-container">
<form name="login-form" id="user" method="post" action="/login/" enctype="multipart/form-data" class="text">
{% csrf_token %}
<div class="title">Enter your credentials</div>
<div class="form-row">
<div class="form-flex">
<div class="field-container">
<div class="field-input-container">
<div class="field-label accent">Username</div>
<div class="field-input">
<input class="field-input-element" type="text" name="username" />
</div>
</div>
<div class="field-help">Your username is always lowercase.</div>
</div>
</div>
<div class="form-flex">
<div class="field-container" style="height: 110px">
<div class="field-input-container">
<div class="field-label accent">Password</div>
<div class="field-input">
<input class="field-input-element" type="password" name="password" />
</div>
</div>
<div class="field-help"></div>
</div>
</div>
</div>
<div class="form-button-container">
<div class="form-error"></div>
<div class="form-message"></div>
<input type="submit" name="submit" value="Accept" class="button form-button"/>
</div>
</form>
</div>
{% endblock %}
In my base (base.html)
<body>
<div id="modal-container">
<div id="modal-overlay">
<div id="modal-items">
</div>
</div>
</div>
<div id="wrapper">
<header>
<div id="header-title" class="text accent">App name</div>
<div id="header-nav">
<nav>
{% if user.is_authenticated %}
Home
Feed {% if request.user.is_superuser %}
Admin {% endif %}
N
<a href="/{{ request.user }}" class="header-avatar-small-a">
<div class="text header-greeting">Hi, {{ user.userprofile.display_name }}</div>
<div class="header-avatar-small">
{% if not user.userprofile.avatar == '' %}
<img src="{{ MEDIA_URL }}users/{{ user }}/avatar" alt=""> {% else %}
<img src="{{ MEDIA_URL }}users/avatar" alt=""> {% endif %}
</div>
</a>
{% else %}
Log in
Create account {% endif %}
</nav>
</div>
<div class="progress">
<div id="header-progress" class="fill"></div>
</div>
</header>
<main>
{% block content %} {% endblock %}
</main>
<footer></footer>
</div>
</body>
</html>
Template source is the template actual HTML, not the file reference

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

Cannot get assign where working in Jekyll template

I have built my website in Jekyll.
The data file is working fine when parsed elsewhere, but when I try to access a particular record using a where clause I get no result.
See the project at https://github.com/ohiweb/ohiweb.github.io
The troublesome page is under portfolio\betimca\index.html
portfolio.yml
projects:
- name: "betimca"
title: "Betimca Subdivision Project"
description: "These beautiful houses in Betimca feature classical elements with modern conveniences. Brick facades are crafted with accents tht stand out for maximum curb appeal. Gables with generous windows allow maximum light to upstairs rooms and add to their distinguished character."
feature: "betimca_1a.jpg"
media: "portfolio/betimca"
images: [betimca_1a.jpg,betimca_1b.jpg,betimca_1c.jpg,betimca_2a.jpg,betimca_2b.jpg,betimca_3a.jpg,betimca_3b.jpg]
tags: ["portfolio", "new construction", "residential", "subdivision"]
index.html
{% assign project = site.data.portfolio.projects | where: "name", "betimca" %}
<section>
<div class="row">
<div class="col col-md-4">
<header class="page-header">
<h1>
{{project.title}}
</h1>
</header>
<p>{{project.description}}</p>
</div>
<div class="col col-md-6 col-md-offset-2">
<img src="/media/{{project.media}}/{{project.feature}}" class="img-responsive img-thumbnail">
</div>
</div>
<hr>
<div class="row">
{% for image in project.images %}
<div class="col col-xs-6 col-sm-4 col-lg-3">
<span class="thumbnail">
<img src="/media/{{project.media}}/{{image}}" alt="{{project.title}} {{image}}">
</span>
</div>
{% endfor %}
</div>
</section>
{% assign project = site.data.portfolio.projects | where: "name", "betimca" %}
This returns an array with one element.
If you want to get the element in project you can do :
{% assign project = site.data.portfolio.projects | where: "name", "betimca" | first %}
And now your page works.

Resources