django bootstrap datetimepicker - javascript

i am trying to implement the datepicker using the django bootstrap datepicker widget, but the datepicker is not showing on the webpage ("welcome.html)
i have passed the form to the views and called the form in the webpage
any help will be appreciated
forms.py
class DateForm(forms.Form):
todo = forms.CharField(
widget=forms.TextInput(attrs={"class":"form-control"}))
date_1=forms.DateField(widget=DatePicker(
options={"format": "mm/dd/yyyy",
"autoclose": True }))
def cleandate(self):
c_date=self.cleaned_data['date_1']
if c_date < datetime.date.today():
raise ValidationError(_('date entered has passed'))
elif c_date > datetime.date.today():
return date_1
def itamdate(self):
date_check=calendar.setfirstweekday(calendar.SUNDAY)
if c_date:
if date_1==date_check:
pass
elif date_1!=date_check:
raise ValidationError('The Market will not hold today')
for days in list(range(0,32)):
for months in list(range(0,13)):
for years in list(range(2005,2108)):
continue
views.py
def imarket(request):
#CREATES A FORM INSTANCE AND POPULATES USING DATE ENTERED BY THE USER
if request.method=='POST':
form = DateForm(request.POST or None)
#checks validity of the form
if form.is_valid():
itamdate=form.cleaned_data['date_1']
return HttpResponseRedirect(reverse('welcome.html'))
return render(request, 'welcome.html', {'form':form})
welcome.html
{% extends 'base.html' %}
{% load bootstrap %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="//cdn.bootcss.com/bootstrap-datetimepicker/4.17.44/js/bootstrap-datetimepicker.min.js"></script>
{% block content %}
<title>welcome</title>
<form action = "{% url "imarket"}" method = "POST" role="form">
{% csrf_token %}
<table>
{{form|bootstrap_horizontal}}
</table>
<div class = "form-group">
<input type ="submit" value= "CHECK" class="form control"/>
</div>
</form>
{% endblock %}

The bootstrap datepicker wasn't working , so i added the jquery datepicker to directly to my forms. py using this answer
my updated forms.py
class DateForm(forms.Form):
todo = forms.CharField(
widget=forms.TextInput(attrs={"class":"form-control"}))
date_1=forms.DateField(widget=forms.DateInput(attrs={'class':'datepicker'}))
my updated welcome.html
{% extends 'base.html' %}
{% load bootstrap %}
{% block content %}
<title>welcome</title>
<form action = "{% url "imarket"}" method = "POST" role="form">
{% csrf_token %}
<table>
{{form|bootstrap}}
<script>
$(document).ready(function() {
$('.datepicker').datepicker();
});
</script>
</table>
<div class = "form-group">
<input type ="submit" value= "CHECK" class="form control"/>
</div>
</form>
{% endblock %}

datepicker should be initialized in the html page.

if you are using bootstrap download datepicker from Datetimepicker for Bootstrap 4
then
in the head section include
font awesome css
boostrap4 css
bootstrap-datetimepicker.min.css
in the body section include
moment.min.js
bootstrap.min.js
bootstrap-datetimepicker.min.js
define your form
from django import forms
class DateRangeForm(forms.Form):
start_date = forms.DateTimeField(required=True)
end_date = forms.DateTimeField(required=True)
in the template render the form
<form action="/your-name/" method="post">
{% csrf_token %}
{{ dt_range_form }}
<input class="btn btn-primary btn-sm" type="submit" value="Refresh">
</form>
in the script section add
$("#id_start_date").datetimepicker();
And here you have your datetimepicker! For me Time icon is still not showing up! Need to debug it.

Related

Django forms - How to change form data with HTML DOM?

I am trying to change a Django form's data by using:
document.getElementById("id_role").innerHTML = "developer"
The CustomUser model has a "role" field that is referenced in the function. By testing the output (with the displayField() function, it appears that document.getElementById("id_role").innerHTML actually references all of the available fields ("choices" given in the models.py).
The goal is for the second function, changeField(), to change the selected data on the form (my goal isn't to change the database's stored data at this point, just the selected form's input).
My question: How do I use document.getElementById().innerHTML to access the specific value that is shown in the form, instead of all of the options for the field?
models.py
TECH_OPTIONS = ( ('developer','DEVELOPER'), ('manager','MANAGER'), ('testing','TESTING'), )
class CustomUser(AbstractUser):
career = models.CharField(max_length=30)
role = models.CharField(choices=TECH_OPTIONS,blank = True, max_length=30)
def __str__(self):
return self.username
html page
{% extends "base.html" %}
{% load bootstrap3 %}
{% block content %}
<h1 id="testTag">{{user.username}}'s Info</h1>
<input onclick="displayField(); changeField();" type="submit" name="" value="TESTING">
<form method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Save" />
</form>
<script type="text/javascript">
function displayField(){
var myFormFields = document.getElementById("id_role").innerHTML
document.getElementById("testTag").innerHTML = myFormFields;
}
function changeField(){
document.getElementById("id_role").innerHTML = "developer"
}
</script>
{% endblock %}
You need to use value rather than innerHTML to change/read the value of a field:
document.getElementById("id_role").value = "developer"

how to delete multiple delete in django

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"),
]

Django: How can I create a dynamic form that changes on user click?

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

How to use "django-autocomplete-light" in inline form

I would like to use an inline model form with a 'django-autocomplete-light field'. I'm a little bit desperate also, because I don't know 'javascript' well.
This is a picture of my form. At first glance, it works as desired:
Unfortunately, only the first field loads correctly. If I add more fields there are errors (see pictures).
This is my form template where I suspect the error, because the first field works correctly as desired.
<div class="container">
<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
<!-- Medication Table -->
<table class="table">
{{ medication.management_form }}
{% for form in medication.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle "row1" "row2" %} formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" value="Submit Form"/>
<script type="text/javascript" src="{% static '/js/core/jquery.3.2.1.min.js' %}"></script>
{{ form.media }}
<!-- script for add, delete, update -->
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'add medication',
deleteText: 'remove',
prefix: 'medication_set'
});
</script>
</div>
After hours googling and going through other answers, what worked for me was this.
I added a key named clone in the defaults of the jquery.formset.js with default value as true.
/* Setup plugin defaults */
$.fn.formset.defaults = {
prefix: 'form', // The form prefix for your django formset
formTemplate: null, // The jQuery selection cloned to generate new form instances
clone: true, // Set this value to false when using autocomplete in formset
addText: 'add another', // Text for the add link
deleteText: 'remove', // Text for the delete link
addCssClass: 'add-row', // CSS class applied to the add link
deleteCssClass: 'delete-row', // CSS class applied to the delete link
formCssClass: 'dynamic-form', // CSS class applied to each form in a formset
extraClasses: [], // Additional CSS classes, which will be applied to each form in turn
keepFieldValues: '', // jQuery selector for fields whose values should be kept when the form is cloned
added: null, // Function called each time a new form is added
removed: null // Function called each time a form is deleted
};
Then replaced the code inside addButton.click() in jquery.formset.js from
row = options.formTemplate.clone(true).removeClass('formset-custom-template')
to
row = options.formTemplate.clone(options.clone).removeClass('formset-custom-template')
Then in the template of the formset, changed formset function from this :
$('#brand_formset_div .parentdiv .form-group').formset({
prefix: '{{ brand_formset.prefix }}',
deleteText: 'Clear',
deleteCssClass: 'shop-now-delete',
addText: 'Add new Brand',
addCssClass: 'btn btn-success ',
});
to this (a clone key as false is inserted along with a function added that is triggered when a new row is inserted.The function hides the extra autocomplete box.)
$('#brand_formset_div .parentdiv .form-group').formset({
prefix: '{{ brand_formset.prefix }}',
clone: false,
deleteText: 'Clear',
deleteCssClass: 'shop-now-delete',
addText: 'Add new Brand',
addCssClass: 'btn btn-success ',
added: function(row) {
$('span .select2-selection--single:odd', row || null).css("display", "none");
}
});
This worked fine for me.

Parameter send from JsonRespond doesnt pass to HTML page , Python django

I have a webapp build in Python 2.6 and Django.
I am trying to send parameters to the HTML page but it seems that the HTML page is refreshing to the default values all the time.
Meaning i can see that movetobi is being called but it looks like the moment movebi return the value the page is reloaded again
View.py
def adminoperation(request):
return render(request,'app/adminoperation.html',{'some_flag':'999999'})
def movetobi(request):
if 'check' in request.POST and request.POST.get('check'):
data= {'newtest':3}
return JsonResponse(data, safe=False)
adminoperation.html
{% extends "app/layout.html" %}
{% block content %}
<p>Adminstration site for FTMS 2017</p>
<h2> {{mssg}}</h2>
<p>{{ mssg2 }} </p>
<p>{{ mssg3 }} </p>
<form id="data_form" method="post" enctype="multipart/form-data">
{% csrf_token %}
<button id="run_reports" type="submit" name="action" value="commit">Run Reports For BI</button>
<br> <br>
<button id="Rollback" type="submit" name="action"
value="commit">Rollback</button>
input type="hidden" id="commitok" name="commitok" value="{{ some_flag }}" />
</form>
{% endblock %}
{% block scripts %}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<script>
$(function () {
$('#run_reports').click(function () {
$.ajax({
type: "POST",
url: 'movetobi',
data: {
'check' : '1',
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function (data){
if (data['newtest']==3) {
confirm("You are trying to run a month that allready exist");
}},
error: function(data){
if (data['newtest']==5) {
confirm("test");
}}
});
});
});
</script>
{% endblock %}
$('#run_reports').click(func) will not prevent the form from being submitted directly by the browser. You have to get the click event and call preventDefault() on it:
$('#run_reports').click(function(evt) {
evt.preventDefault();
# your code here
})

Categories