Doubt:
Here I have mentioned Html and output Image.
If I click select all option (checkbox) it will select all image but my doubt was how to delete all images once I click delete button.
Html
{% for j in img %}
<h4>
Select All
<input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" />
</h4>
<button class="btn btn-danger" action=" ">Delete</button>
<div class="col">
{% if i.placename == j.gallery_place %}
<div class="show-image">
<img src="{{j.gallery_image.url}}" style="height:130px; width:130px;" />
<tag class="one" style="margin:8%">
<input type="checkbox" name="selected[]" value="{{j.id}}" />
</tag>
</div>
{% endif %}
</div>
{% endfor %}
image
enter image description here
You can use a FormView in Django and process them as follows. You need to create a form with the checkboxes first:
# forms.py
class CheckboxesForm(forms.Form):
checkboxes = forms.ModelMultipleChoiceField(
MyModel.objects.all(),
widget=forms.CheckboxSelectMultiple)
Then you need to write your own FormView and override the form_valid() method to perform the deletion of the selected objects. If you want to define objects for which you have checkboxes, you can override the get_form() method.
# views.py
class MyListView(ListView):
"""
View displaying a list of objects, you will redirect here after successfully deleting the objects you want
"""
model = MyModel
class MyView(FormView):
"""
Class based view taking care of rendering the form and processing it after posting. Finally, redirects you to your list view defined above.
"""
form_class = MyForm
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['objects'] = MyModel.objects.all() # Customize this queryset to your liking
return context
def get_form(self, form_class=None):
form = super().get_form(form_class)
form.fields['checkboxes'].queryset =
MyModel.objects.all() # Customize this queryset to determine for which objects you want to display checkboxes
return form
def form_valid(self, form):
qs = myModel.objects.filter(
pk__in=list(map(int, self.request.POST.getlist('checkboxes'))))
qs.delete()
return HttpResponseRedirect(reverse_lazy('someurl'))
Your template will look like this (adapted from what you posted)
# template.html
{% for j in objects %}
<h4>
Select All
<input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" />
</h4>
<button class="btn btn-danger" action=" ">Delete</button>
<div class="col">
{% if i.placename == j.gallery_place %}
<div class="show-image">
<img src="{{j.gallery_image.url}}" style="height:130px;
width:130px;" />
<tag class="one" style="margin:8%">
<div class="form-checkbox"><input type="checkbox" name="checkboxes" value="{{ j.pk }}">
</tag>
</div>
{% endif %}
</div>
{% endfor %}
Finally, hook up the urls.
# urls.py
from django.conf.urls import include, url
from.views import MyView, MyListView
urlpatterns = [
url(r'^listdelete/$', MyView.as_view(), name="delete-list"),
url(r'^mylist/$, MyListView.as_view(), name="someurl"),
]
Related
{% assign type_bonbon = "Sans sucre, Gélifié, Guimauve, Nougat, Acide, Doux" | split : ", " %}
<section class="page__content">
{% capture contact_form %}
<div class="contact">
{% form 'contact', class: 'contact__form' %}
<div class="form__control">
<label class = "form__label" for="contact__type_bonbon">Types de bonbons</label>
{% for type in type_bonbon %}
<div class = "checkbox">
<input type="checkbox" id="contact__type_bonbon" name="contact[type]" value="{{type_bonbon}}">{{type}}
</div>
{% endfor %}
</div>
{% endform %}
</div>
{% endcapture %}
</section>
Hello everyone,
I am struggling to Get every checked values within the checkbox.
Right now im getting only the last checked value
I know in PHP we would use the GET method in order to put the "checked" method to every checkbox checked, however, idk how to proceed in shopify.
Thank you again
I just checked and I was able to replicate the behavior that you mentioned above about receiving only the last checked value. I don't know if it is a bug or feature from Shopify, but you can use a workaround like below where each field is named differently. Another minor thing is the ID attribute needs to be unique while it generates the same in your for loop above. Besides, that for value it should have been value="{{type}}" instead of value="{{type_bonbon}}" as type_bonbon is an array.
{% assign type_bonbon = "Sans sucre, Gélifié, Guimauve, Nougat, Acide, Doux" | split : ", " %}
<section class="page__content">
{% capture contact_form %}
<div class="contact">
{% form 'contact', class: 'contact__form' %}
<div class="form__control">
<label class = "form__label" for="contact__type_bonbon">Types de bonbons</label>
{% for type in type_bonbon %}
<div class = "checkbox">
<input type="checkbox" name="contact[type-{{type}}]" value="{{type}}">{{type}}
</div>
{% endfor %}
</div>
{% endform %}
</div>
{% endcapture %}
</section>
Only this line of code is changed, to generate new field name for each type.
<input type="checkbox" name="contact[type-{{type}}]" value="{{type}}">{{type}}
I want to implement dynamic multiple image upload for an application in Django. I got to know that Django doesn't have any in-built support for that and external libraries have to be used.
I followed the blog - https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html
But the result I'm getting is nowhere close to what is expected.
Starting with settings.py
import os
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
models.py
class Images(models.Model):
file = models.FileField(upload_to='profile_images')
category = models.CharField(max_length=20, blank=False)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.category
forms.py
class ImagesForm(forms.ModelForm):
class Meta:
model = Images
fields = ['file',]
upload.html
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<form id="category_form" method="post" action="/rango/upload/" enctype="multipart/form-data">
{% csrf_token %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/vendor/jquery.ui.widget.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/jquery.iframe-transport.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/jquery.fileupload.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/jquery.fileupload.js"></script>
{# 1. BUTTON TO TRIGGER THE ACTION #}
<button type="button" class="btn btn-primary js-upload-photos">
<span class="glyphicon glyphicon-cloud-upload"></span> Upload photos
</button>
{# 2. FILE INPUT TO BE USED BY THE PLUG-IN #}
<input id="fileupload" type="file" name="file" multiple
style="display: none;"
data-url="{% url 'upload' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
{# 3. TABLE TO DISPLAY THE UPLOADED PHOTOS #}
<table id="gallery" class="table table-bordered">
<thead>
<tr>
<th>Photo</th>
</tr>
</thead>
<tbody>
{% for photo in photos %}
<tr>
<td>{{ photo.file.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="modal fade" id="modal-progress" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Uploading...</h4>
</div>
<div class="modal-body">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;">0%</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
views.py
def upload(request):
photos_list = Images.objects.all()
if request.method == 'POST':
form = ImagesForm(request.POST,request.FILES)
if form.is_valid():
photo = form.save()
data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
else:
data = {'is_valid': False}
return JsonResponse(data)
return render(request, 'rango/upload.html', {'photos': photos_list},)
The output that I get for the /upload/ page is
As you can see, only text is getting display for upload button and uploading progress bar and it's not actually working.
My guess here is that the jQuery libraries aren't getting included or/and JavaScript code isn't working. I am a backend engineer, so please excuse this might be silly question about frontend.
Shall be thankful if someone helps with code specificities.
I'm making a workout calendar website where a user can add workouts with varying amounts of lift, sets and reps, etc. Thus, I need a form that adds a field when a user clicks a button. I've made a template and some javascript to describe what it is I want to achieve exactly:
url:
url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/$', views.add_workout, name = 'add_workout')
template:
{% block hidden %}
{% include "workoutcal/liftrow.html" %} {# To be used by Javascript #}
{% include "workoutcal/cardiorow.html" %}
{% endblock %}
<form action="{% url 'add_workout' date.year date.month date.day %}" method="post">
<div class="row">
<div class="col-xs-2">
<p id="date">{{ date.year }}-{{ date.month }}-{{ date.day }}</p>
<input type="hidden" name="date" value="{{ date }}">
</div>
</div>
<h2 class="col-xs-12">Lifts</h2>
<div id="liftrows">
{% for i in range %}
{% include "workoutcal/liftrow.html" %}
{% endblock %}
</div>
<div class="row">
<div class="col-xs-0"></div>
<label class="col-xs-2"><button type="button" id="addliftbutton">One more lift</button></label>
</div>
<h2 class="col-xs-12">Cardio</h2>
<div id="cardiorows">
{% include "workoutcal/cardiorow.html" %}
</div>
<div class="row">
<label class="col-xs-2"><button type="button" id="addcardiobutton">One more cardio</button></label>
</div>
<div class="row">
<div class="col-xs-10"></div>
<label class="col-xs-2"><input type="submit" id="submitbutton" value="Save Workout"></label>
</div>
</form>
javascript:
//Adding onclick to buttons
document.getElementById('addliftbutton').onclick = addLiftRow;
document.getElementById('addcardiobutton').onclick = addCardioRow;
for (var i=0; i<setsBoxes.length; i++){
setsBox = setsBoxes[i];
setsBox.onchange = insertRepFields;
}
function addLiftRow(){
var liftRowElements = document.getElementById('liftrows');
var hidden_liftrow = document.getElementById('hidden').getElementsByClassName('lift')[0];
var new_liftrow = hidden_liftrow.cloneNode(true);
liftRowElements.appendChild(new_liftrow);
}
function addCardioRow(){
var cardiorows = document.getElementById('cardiorows');
var hidden_cardiorow = document.getElementById('hidden').getElementsByClassName('cardio')[0];
var new_cardiorow = hidden_cardiorow.cloneNode(true);
cardiorows.appendChild(new_cardiorow);
}
function insertRepFields(){} // big function that inserts as many input fields as the number inside the box whose event called the function.
2 questions:
1. Is there a better way to do this in Django?
2. If this is the best way, how do I go about sending the data of my massive form back to django? Since I don't know exactly how many fields there will be, I don't know how to create a form that accepts a variable amount of fields, and fields within fields.
Here's how a filled-in form could look:
The best way to accomplish that is inserting inputs with the same name and then in Django get all those inputs as a list like:
def view(request):
inputs = request.POST.getlist('your_input_name')
for i in inputs:
Model.objects.create() # Save your model
I've built dynamic forms using django formsets and javascript, but unfortunately on submitting the form only the first form is submitted. I'd like all dynamically added forms to be submitted also. Any help would be appreciated.
Views:
def routestepinfo(request):
class RequiredFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
super(RequiredFormSet, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False
RouteStepFormSet = formset_factory(RouteStepForm, formset=RequiredFormSet, extra=1, can_order=False, can_delete=True)
if request.method == 'POST':
formset = RouteStepFormSet(request.POST)
if formset.is_valid():
for form in formset.forms:
form.save()
print 'apple'
return redirect("/buildpage/")
else:
formset = RouteStepFormSet()
return render(request, "buildpage/routestepinfo.html", {'formset' :formset})
HTML
<form id= "myForm" method = 'POST' action="{% url 'buildpage:routestepinfo' %}" enctype="multipart/form-data">{% csrf_token %}
{{ formset.management_form }}
<div id="form_set">
{% for form in formset %}
<table class='no_error'>
<tbody>.
{{form.as_table}}
</tbody>
</table>
{% endfor %}
</div>
<p><input type = "button" value = "Add another step" id = "add_more" ></p>
<div id="empty_form" style="display:none">
<table class='no_error'>
{{ formset.empty_form.as_table }}
</table>
</div>
<div id="forms"></div>
<p> </p>
<p> </p>
<input type = "submit" name = "Submit Steps">
</form>
JS Clone:
<script>
$('#add_more').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
Fixed it ! Only took a week. Here's how it worked eventually. Views are largely unmodified, just added commit=False to save the list.
def routestepinfo(request, slug=None):
RouteStepFormSet = formset_factory(RouteStepForm, formset = RequiredFormSet, extra=1)
if request.method == 'POST':
formset = RouteStepFormSet(request.POST)
print formset
if formset.is_valid():
for form in formset.forms:
form_item = form.save(commit=False)
print form
form_item.save()
messages.success(request, "Record created")
return redirect ("/buildpage/")
else:
formset = RouteStepFormSet()
return render(request, "buildpage/routestepinfo.html",{'formset':formset})
Javascript was the main thing that changed, with quite a few additions and quite a bit of SO help. The prefix was the first issue, and that was fixed by using formset.empty_form and modifying it from there. Another vital part was updating the total forms, which fixed the saving issue.
<script>
$(document).ready(function() {
$('.add-item').click(function(ev) {
ev.preventDefault();
var count = $('#items-form-container').children().length;
var tmplMarkup = $('#item-template').html();
var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);
$('div#items-form-container').append(compiledTmpl);
// update form count
$('#id_form-TOTAL_FORMS').attr('value', count+1);
$('html, body').animate({
scrollTop: $("#add-item-button").position().top-200
}, 800);
});
});
</script>
Finally the html. This combined some of my own stuff with a very helpful SO post(forgot the question it came from), where formset is generated as an empty form and cloned from there.:
<div type="text/html" id="item-template">
<table>
{{ formset.empty_form.as_table }}
</table>
</div>
<font face = Flexo>
<form id= "myForm" method = 'POST' action="{% url 'buildpage:routestepinfo' %}" enctype="multipart/form-data">{% csrf_token %}
{{ formset.management_form }}
<div id="items-form-container">
{% for form in formset.forms %}
<div id="item-{{ forloop.counter0 }}">
<table>
{{form.as_table}}
<table>
</div>
{% endfor %}
</div>
Add Step
<input type = "submit" name = "Submit Steps">
</form>
Hope this helps some people. Cheers
I'm trying to create my first ajax function in Django.
I want to change my code using JQuery, the idea is pretty simple:
User type a subject name and this name is displayed in subject-list below the form,
The problem is I don't really know what to type in JQuery function.
JQuery:
function create_subject() {
$("input").focus(function(){
var subject = $(this).val();
$(".btn-create").click(function(){
/* What I need to write in here */
});
});
}
In HTML "subjects" refer to database.
HTML
<div id="subjects-list">
{% if user.username %}
<ul>
{% if subjects %}
<form method="post" action=".">{% csrf_token %}
{% for subject in subjects %}
-------- TYPED TEXT SHOULD BE HERE --------> <li>{{ subject.name }}</li>
{% endfor %}
</form>
{% else %}
<p>No Subjects for this user</p>
{% endif %}
</ul>
{% else %}
You are in else
{% endif %}
</div>
That's how HTML looks in "View Page Source"
<div id="create-subject">
<form method="post" action="."> <div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='cfbd1893742c3ab9936bacaae9653051' /></div>
<p><label for="id_name">Subject Name:</label> <input id="id_name" type="text" name="name" size="9" /></p>
<input type="button" name="subject-create-b" value="Create Subject" class="btn-create"/>
</form>
</div>
<div id="subjects-list">
<ul>
<form method="post" action="."><div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='cfbd1893742c3ab9936bacaae9653051' /></div>
<li>Math 140<span id="subject-link"></span></li>
</form>
</ul>
</div>
</div>
And that's my form
forms.py
class SubjectCreationForm(forms.Form):
name = forms.CharField(label="Subject Name", widget=forms.TextInput(attrs={'size':9}))
class Meta:
exclude = ('created_by', 'created_time', 'num_of_followers', 'vote')
def clean_name(self):
name = self.cleaned_data['name']
if len(name)>1:
return name
else:
raise forms.ValidationError("Subject name should be longer")
In order to do what (I think) you want to do which is some basic AJAX using Django as your backend, you'll need the following:
A view which returns the data you want to load
There are a number of ways you can represent the data, but to keep it simple, I'll use HTML.
Javascript to load that view (using JQuery if you like)
Your code might look like this for the first part:
urls.py:
...
(r'^get-subjects/$', 'yourapp.views.get_subjects'),
...
views.py:
...
def get_subjects(request):
subjects = # code to fetch your subjects.
return render_to_response('subjects_template.html', {'subjects': subjects})
...
subjects_template.html:
{% for subject in subjects %}
<li>{{ subject.name }}</li>
{% endfor %}
For the second part, it might look like this:
main_template.html:
...
<ul id="subjects-list"></ul>
<script>
function loadSubjects() {
$.ajax({
url: "/get-subjects",
success: function (data) {
$("#subjects-list").html(data);
}
});
}
</script>
...
[1] render_to_response()
[2] jQuery.ajax()
This will get you most the way there. When you want to reload the list, you call the loadSubjects() function.
As far as creating the subjects go, that is a different thing. What you'll want to look into is how to do an HTML form submission without leaving the page. There are plenty of tools and libraries to do that stuff with a nice api. If you want to stick with JQuery, you might consider this plugin for a nicer api.
function create_subject() {
$("input").focus(function(){
var subject = $(this).val();
$(".btn-create").click(function(){
$('#subjects-list').append(subject);
});
});
}
that said, you probably don't want to assign the click handler every time the input is focused. i'd move that out of the focus handler.