Populating dropdown in Django using Ajax - django

I have several dropdowns in my form, which I am looking to populate using Ajax from backend. Given below are the relevant code segments:
HTML:
<div class="row">
<div class="col-xs-6">
<div class="col-xs-6">
<label name="start_date" class="control-label" style="width:35%">Start date</label>
<input type="date" style="color:black;width:100px" ></input>
</div>
</div>
<div class="col-xs-6">
<label name="end_date" class="control-label" style="width:35%">End Date(Default: Current Date)</label>
<input style="color:black;width:100px" type="date"></input>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<label name="fruit" class="control-label" style="width:35%; padding-left:15px">Select a Fruit</label>
<select style="width:150px;height:30px">
{% for option in options.fruit %}
<option value="{{ option }}">{{ option }}</option>
{% endfor %}
</select>
</div>
<div class="col-xs-6">
<label name="vendor" class="control-label" style="width:35%">Select a vendor</label>
<select style="width:150px;height:30px">
{% for option in options.vendor %}
{{ option }}
<option value="{{ option }}">{{ option }}</option>
{% endfor %}
</select>
</div>
</div>
{% block script %}
<script>
document.onload = function(){
$.ajax({
url : window.location.href,
type:'GET',
cache:false,
data:{type:'formdata'},
success:function(res){
if(typeof res.options == 'undefined'){
self.options = res.options;
}
if(typeof res.options.start_date == 'undefined'){
self.form.start_date = res.options.start_date;
}
if(typeof res.options.end_date == 'undefined'){
self.form.end_date = res.options.end_date;
}
if(typeof res.options.fruit == 'undefined'){
window.fruit = res.options.fruit;
}
if(typeof res.options.vendor == 'undefined'){
window.vendor = res.options.vendor;
}
},
error : function(err){
self.message = "Error getting data for the form";
}
});
}
</script>
{% endblock %}
Both the drop downs are independent of each other. The data is being given at the front end through this view:
class Search(View):
def get(self, request):
if request.GET.get('type') == 'formdata':
options = {'fruit': [], 'vendor': []}
try:
cursor = connections['RDB'].cursor()
options['end_date'] = today.strftime('%Y-%m-%d')
last_week_date = today - timedelta(days=7)
options['start_date'] = last_week_date.strftime('%Y-%m-%d')
options['fruit'] = [a[0] for a in cursor.fetchall()]
options['vendor'] = [a[0] for a in cursor.fetchall()]
return JsonResponse({'options': options})
The back end is working perfectly fine, the options dictionary is getting populated as I expected it to. However the drop down options are not showing up on the front end. Where am I going wrong? Any help is greatly appreciated.

Maybe try using select2 it's a pretty good utility for populating select boxes through Ajax, even has a search functionality in built. Here's a simple example.
html -
<html>
<head>
<title>Using Select2</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Select2 CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<div class="jumbotron">
<div class="container bg-danger">
<div class="col-md-6">
<label>Single Select2</label>
<select class="js-data-example-ajax"></select>
</div>
</div>
</div>
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Select2 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script>
$('.js-data-example-ajax').select2({
ajax: {
url: 'https://api.github.com/search/repositories',
dataType: 'json'
// Additional AJAX parameters go here; see the end of this chapter for the full code of this example
}
});
</script>
</body>
</html>
Don't forget to import the relative JS and CSS CDN's.

Related

How to loop over Chart.js with Django list view

I am using a Django List View, and I am trying to iterate through multiple objects and display percentage values in a Chart.JS gauge.
However, although I am iterating the names of the gauge id's by using a for loop counter, I am only ever getting the first iteration of the chart.js object rendering on my screen. My initial thoughts are that similar to how I am dynamically creating new canvas ids for the chart.js objects, I should be doing a similar thing for the variable I am trying to pass into the chart object e.g. reduction overall, but I am not having any luck. Your feedback is welcome.
Views.py
class PerformanceDetailView(ListView):
template_name = 'performance_detail.html'
model = Performance
context_object_name = 'performance'
def get_queryset(self, **kwargs):
code = self.kwargs.get('code')
return Performance.objects.filter(code=code)
Performance_detail.html
<section class="projects pt-4 col-lg-12">
{% for item in performance %}
<div class="container-fluid pt-2 col-lg-12">
<!-- Project--><div class="project" >
<div class="row bg-white has-shadow" style="height: 14rem">
<div class="left-col col-lg-2 d-flex align-items-center justify-content-between">
<div class="project-title d-flex align-items-center">
<div class="has-shadow"><img src="{% static 'img/avatar-2.jpg' %}" alt="..." class="img-fluid"></div>
</div>
</div>
<div class="right-col col-lg-2 align-items-center vertical-center">
<div class="text">
<h3 class="h2 pt-2">{{item.brand}} {{item.style}}</h3>
<p class="text-muted">{{item.package_type| capfirst}} package, round {{item.testing_round}}</p>
<p class="text-muted">Item size: {{item.size}}</p>
</div>
</div>
<div class="right-col col-lg-8 align-items-center vertical-center">
<div class="row mt-5">
<div class="col-md-3">
<div class="gauge-container">
<canvas id="gauge1-{{ forloop.counter }}" class="gauge-canvas"></canvas><span id="gauge1Value-{{ forloop.counter }}" class="gauge-label"></span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{{ item.reduction_overall|json_script:"reduction_overall" }}
{{ for_loop_counter|json_script:"for_loop_counter" }}
{% endfor %}
</section>
{% endblock content %}
Block JS within package_detail.html
<!-- Gauge.js-->
<script src="{% static 'vendor/gaugeJS/gauge.min.js' %}"></script>
<script>
$(function () {
var reduction_overall = JSON.parse(document.getElementById('reduction_overall').textContent);
var for_loop_counter = JSON.parse(document.getElementById('for_loop_counter').textContent);
// Gauges
var gauge1 = document.getElementById('gauge1-'+for_loop_counter);
opts.colorStop = "#864DD9";
var gaugeObject1 = new Donut(gauge1).setOptions(opts);
gaugeObject1.maxValue = 100; // set max gauge value
gaugeObject1.setMinValue(0); // set min value
gaugeObject1.set(reduction_overall); // set actual value
gaugeObject1.setTextField(document.getElementById("gauge1Value-" + for_loop_counter));
});
</script>
{% endblock js %}
This was solved by including the JavaScript in the main block content and dynamically naming the gauge elements themselves.
var func_name = "container-{{forloop.counter}}";
func_name = new Donut(gauge1).setOptions(opts);
I posted a full example to a similar problem here Chart JS and Django loop

FlatPicker in Django Edit custom form showing time, only days

I have a Django app, with new template where datetimepicker works well. I created an edit template but the widget do not load automatically, so I added them. But for some reason, i do not know how to bring the datetimepicker, I can only get the datepicker.
Does anybody knows please ?
The precise line in the edit template looks like:
<div>
<input id="Restriction_Start_Date_id" type="text" name="Restriction_Start_Date" value="{{ restricted_name_obj.Restriction_Start_Date|date:'n/j/Y G:i' }}" class="form form-control datepicker" >
</div>
While on the new template I have :
<div>{{ form.Restriction_Start_Date.label_tag }}</div>
<div>
{{ form.Restriction_Start_Date.errors }}
{{ form.Restriction_Start_Date }}
</div>
Solution found, I used the CDN and the following :
<link href="https://cdn.jsdelivr.net/npm/flatpickr#4.5.2/dist/flatpickr.min.css"type="text/css" media="all" rel="stylesheet">
<div>
<input type="hidden" name="Restriction_Start_Date" required="" id="Restriction_Start_Date" fp_config="{"id": "fp_14", "picker_type": "DATETIME", "linked_to": "fp_13", "options": {"mode": "single", "dateFormat": "Y-m-d H:i:S", "altInput": true, "enableTime": true}}"class="flatpickr-input" value="{{ restricted_name_obj.Restriction_Start_Date|date:'n/j/Y G:i' }}">
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/flatpickr#4.5.2/dist/flatpickr.min.js"></script>
<script type="text/javascript"src="https://cdn.jsdelivr.net/gh/monim67/django-flatpickr#1.0.0/static/js/django-flatpickr.js"></script>
(Not beautiful but it will do the job for now.

how to create a function update using django and ajax

i have a django project that include a form where user insert data and save it into database using django function and ajax call.
without using the ModelForm in django.
now i want to allow the user to update the form that he choose and once the user choose the form the fields must be displaying the existing data.
until now this was the create process.
i know that the update process will need the id of the object in order to be able to update the selected record.
the error :
'suspect' object is not iterable Request Method: GET Request
URL: http://127.0.0.1:8000/blog/update/23/ Django Version: 2.1.3
Exception Type: TypeError Exception Value: 'suspect' object is not
iterable Exception Location: C:\Users\LT
GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\defaulttags.py
in render, line 165 Python Executable: C:\Users\LT
GM\AppData\Local\Programs\Python\Python37\python.exe
urls.py
path('update/<int:pk>/',update,name = 'update'),
update.html
{% extends "base.html" %}
{% load static %}
{% block body %}
<head>
<link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}">
<link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}">
<link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}">
<link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}">
<link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}">
<meta name= "viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script>
<title>Welcome</title>
</head>
<body>
<div class="lines">
<div class="line"></div><div class="line"></div>
<div class="line"></div><div class="line"></div>
<div class="line"></div><div class="line"></div><div class="line"></div>
</div>
{% for suspect in instance %}
<form enctype="multipart/form-data">
<div id='left-column-Input' class="formInput" include="select()">
<div class="forminputs">
<input type="text" id="fname" name="fname" autocomplete="off" required />
<label for="fname" class="label-name">
<span class="content-name" name="fname">{{suspect.suspect_name}}</span>
</label>
</div>
<div class="forminputs">
<input type="text" id="lname" name="lname" autocomplete="off" required />
<label for="lname" class="label-name">
<span class="content-name" name="lname">{{suspect.suspect_last_name}}</span>
</label></div>
<div class="forminputs">
<input type="text" id="fatherName" name="fatherName" autocomplete="off" required />
<label for="fatherName" class="label-name">
<span class="content-name" name="fatherName">{{suspect.suspect_father_name}}</span>
</label></div>
<div class="forminputs">
<input type="text" id="motherName" name="motherName" autocomplete="off" required />
<label for="motherName" class="label-name">
<span class="content-name" name="motherName">{{suspect.suspect_mother_name}}</span>
</label></div>
<div class="formSelect">
<select id="gender" name="gender" required>
<option value="">{{suspect.gender}}</option>
<option value="1">male</option>
<option value="2">female</option>
</select></div>
<div>
<textarea id="content" name="textarea" class="textArea" placeholder="content">{{suspect.content}} </textarea>
</div>
<div class="home-Button">
<button id="edit" name="edit" type="submit">Edit</button>
<button id="clear" name="clear" type="submit">Clear</button>
</div>
</div>
{% endfor %}
<script type="text/javascript">
$(document).ready(function(){
$("#edit").on('click',function(event){
event.preventDefault()
fName=$('#fname').val()
lName = $('#lname').val()
fatherName = $('#fatherName').val()
motherName = $('#motherName').val()
gender = $('#gender').val()
content=$('#content').val()
$.ajax({
url:'/blog/update',
method:'POST',
data: {
FName: fName,
LName: lName,
FatherName: fatherName,
MotherName: motherName,
Gender: gender,
content:content,
// data:data
},
headers:{
'X-CSRFToken':'{{csrf_token}}'
}
}).done(function(msg){
location.href='/blog/list'
}).fail(function(err){
alert(err)
})
})
})
</script>
</form>
</body>
{% endblock %}
views.py
def update(request,pk):
#deny anonymouse user to enter the detail page
if not request.user.is_authenticated:
return redirect("login")
else:
suspect = get_object_or_404(suspect, pk=pk)
if request.method =="POST":
suspect = suspect()
suspect.suspect_name = request.POST['FName']
suspect.suspect_last_name = request.POST['LName']
suspect.suspect_father_name = request.POST['FatherName']
suspect.suspect_mother_name = request.POST['MotherName']
suspect.gender = request.POST['Gender']
suspect.content = request.POST['content']
print(suspect.suspect_name)
suspect.save()
context = {
"title":member.member_name,
"instance":member,
}
return render(request,'blog/update.html',context)
i will appreciate any help
I will give you a simple example that you can extend for your case.
In the template where the user have a link to update his profile :
Update Profile
in your urls.py
path('update_profile/', views.ProfileUpdate, name='Profile-Update')
in views.py
def ProfileUpdate(request):
current_user = request.user
if request.method == 'POST':
get_username = request.POST.get('username', '').strip()
suspect.objects.filter(pk=current_user.pk).update(username=get_username)
return HttpResponse('Profile Updated')
else:
return render(request, 'prorile_update_form.html', {'current_user': current_user})
in prorile_update_form.html :
<form class="update_profile">
{{ csrf_token }}
<input type="text" name="username" value="{{ current_user.username }}">
<button class="submit_update">Save changes</button>
</form>
<!-- So the current user username will be displayed on the input as a value -->
<script type="text/javascript">
$('.submit_update').on('click', function(){
$.ajax({
url: '/update_profile/',
method : 'POST',
data: $('.update_profile').serialize(),
beforeSend: function() {
// things to do before submit
},
success: function(response) {
alert(response)
}
});
return false;
});
</script>
If the user have a different model that he can update so you may want to pass the id of the form as a variable in the url like this :
path('update_profile/<int:pk>', views.ProfileUpdate, name='Profile-Update')
And you interpret the variable on your view like this :
def ProfileUpdate(request, pk):
you can use the pk to fetch the required model and than make all the required updates based on the form that you will provide.

Using two different templates for search results - Haystack

I am totally confused how I can use two different template files for the search results. Suppose I have two different pages for searching and I want to have different decorations for each page search results.
This search bar is in one page:
<div class="main-header_search">
<form method="get" action="/search1" id="header_find_form" class="main-search yform" role="search"
data-component-bound="true">
<div class="arrange arrange--middle arrange--6">
<div class="arrange_unit" style="width: 100%;">
<div class="main-search_suggestions-field search-field-container find-decorator">
<label class="main-search_pseudo-input pseudo-input">
<span class="pseudo-input_text">Find</span>
<span class="pseudo-input_field-holder">
<input autocomplete="off" type="search" id="id_q" maxlength="64" name="q"
placeholder="Cheap dinner, Cafe" value=""
class="main-search_field pseudo-input_field"
aria-autocomplete="list" tabindex="1" data-component-bound="true">
</span>
</label>
<div class="main-search_suggestions suggestions-list-container search-suggestions-list-container hidden"
data-component-bound="true">
<ul class="suggestions-list" role="listbox" aria-label="Search results"></ul>
</div>
</div>
</div>
<div class="arrange_unit main-search_actions">
<button class="ybtn ybtn-primary main-search_submit" id="header-search-submit"
tabindex="3"
title="Search" type="submit" value="search">
<i class="i ig-common_sprite i-search-common_sprite"></i>
</button>
</div>
</div>
</form>
</div>
And this is in another page:
<form method="get" name="business_search_form" class="yform business-search-form"
action="/search2" role="search">
<div class="arrange arrange--6 arrange--stack">
<div class="arrange_unit arrange_unit--fill">
<div class="arrange arrange--equal arrange--6 arrange--stack">
<div class="arrange_unit">
<label class="responsive-visible-small-block hidden-non-responsive-block">Business
Name</label>
<div class="pseudo-input business-find-decorator">
<div class="flex-container-inline">
<div class="label responsive-hidden-small">Business Name</div>
<div class="flex-box input-holder">
<input class="landing-search-biz-name" placeholder="e.g. Mel's Diner"
name="q" autocomplete="off" type="text">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="arrange_unit nowrap">
<button type="search" value="search"
class="ybtn ybtn-primary yform-search-button ybtn-full-responsive-small"><span><span
class="i-wrap ig-wrap-common i-search-dark-common-wrap"><i
class="i ig-common i-search-dark-common"></i> Get Started</span></span></button>
</div>
</div>
</form>
I would like to use something like this in urls.py to have two different templates for each search results:
(r'^search1/', include('haystack.urls'), name='template1'),
(r'^search2/', include('haystack.urls'),name='template2'),
I am using simple haystack backend in my setting.py:
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
},
}
Here is how I would do it:
First, create a search form that inherits haystack's SearchForm:
class ItemSearchForm(SearchForm):
def search(self, request):
items = super(ItemSearchForm, self).search().models(Item) // Item is your model name
shops = super(ItemSearchForm, self).search().models(Shop)
return {'items': items, 'shops': shops}
Second, create views that uses this form:
def searchItems(request):
form = ItemSearchForm(request.GET)
results = form.search(request)
return render(request, 'search/search.html', {
'items': results['items']
})
def searchShops(request):
form = ItemSearchForm(request.GET)
results = form.search(request)
return render(request, 'search/search.html', {
'shops': results['shops']
})
Please note that these two views use different return values. You can change it to fix your situation.
Then, configure urls:
(r'^search1/', 'views.search1', name='search1'),
(r'^search2/', 'views.search2', name='search2'),
The only thing left to do, write your indexes file and documents. This should do it.

Ajax, Django, Jquery Model Form

Built a successful working ModelForm and its fully functional.
My next step was to add Ajax to it and it also worked out pretty well. The Jquery that I used was 1.3.2 version which is pretty old but it worked.
The problem came up when I tried to add bootstrap 2 DATE fields.
Using CHECKIN & CHECKOUT values that I have added to my form and it worked.
It required higher version of jquery so I used the recent one 1.9.1.
But when I used it my form is working except 1 little issues when I submit the form
and there not filled out required fields it will show me those fields but SUBMIT button is
disabled. When I use jquery 1.3.2 all is working 100% except the 2 fields for Bootstrap
DATEPICKER that requires higher jquery version.
Input Fields in the Form: Departure & Return are Date Picker Fields
I didnt include the Bootstrap Scripts they are same from the Bootsrap site.
When I use:
<script src="/media/js/jquery/1.9.1.jquery.min.js" type="text/javascript"></script>
Departure & Return are Date Picker Fields are Working but after submitting it with empty
other fields - it will show you which fields are required but Submit button is disabled.
If I use:
<script src="/media/js/jquery/1.3.2.jquery.min.js" type="text/javascript"></script>
Form is working with ajax 100% but I cant use Departure & Return are Date Picker Fields
(which give me choice to select date - I have to manually type it).
For reference I used this tutorial.
Look at the Category ModelForm Ajax
My question is I can I achieve this form to be working on 1.9.1 Jquery Version with also Date
picker Fields that I can choosed from the calendar.
At the bottom I am including screenshots.
Here is the code:
MODELS.PY
TRIP_TYPES = (
('one way', 'One Way'),
('round trip', 'Round Trip'),
('multi-leg', 'Multi-Leg'),
)
class Request_Quote(models.Model):
trip_type = models.CharField(max_length=10, choices=TRIP_TYPES, default='one way')
company_name = models.CharField(max_length=200)
individual_name = models.CharField(max_length=200)
phone = models.CharField(max_length=200)
email = models.CharField(max_length=200)
from_country = models.CharField(max_length=200)
to_country = models.CharField(max_length=200)
from_city = models.CharField(max_length=200)
to_city = models.CharField(max_length=200)
departure_date = models.CharField(max_length=200)
return_date = models.CharField(max_length=200)
number_of_passengers = models.CharField(max_length=200)
VIEWS.PY
def quote(request):
if request.method == "POST":
form = Request_QuoteForm(request.POST)
## Handle AJAX ##
if request.is_ajax():
if form.is_valid():
form.save()
# Get a list of Categories to return
quotes = Request_Quote.objects.all().order_by('individual_name')
# Create a dictionary for our response data
data = {
'error': False,
'message': 'Request Quote Added Successfully',
# Pass a list of the 'name' attribute from each Category.
# Django model instances are not serializable
'quotes': [q.individual_name for q in quotes],
}
else:
# Form was not valid, get the errors from the form and
# create a dictionary for our error response.
data = {
'error': True,
'message': "Please try again!",
'trip_type_error': str(form.errors.get('trip_type', '')),
'company_name_error': str(form.errors.get('company_name', '')),
'individual_name_error': str(form.errors.get('individual_name', '')),
'phone_error': str(form.errors.get('phone', '')),
'email_error': str(form.errors.get('email', '')),
'from_country_error': str(form.errors.get('from_country', '')),
'to_country_error': str(form.errors.get('to_country', '')),
'from_city_error': str(form.errors.get('from_city', '')),
'to_city_error': str(form.errors.get('to_city', '')),
'departure_date_error': str(form.errors.get('departure_date', '')),
'return_date_error': str(form.errors.get('return_date', '')),
'number_of_passengers_error': str(form.errors.get('number_of_passengers', '')),
}
# encode the data as a json object and return it
return http.HttpResponse(json.dumps(data))
if form.is_valid():
form.save()
return http.HttpResponseRedirect('/request-quote/')
else:
form = Request_QuoteForm()
quotes = Request_Quote.objects.all().order_by('individual_name')
return render_to_response('quote.html', {'title': 'Request Quote', 'form': form, 'quotes': quotes}, context_instance=RequestContext(request))
TEMPLATES:
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
$("#add_cat").ajaxStart(function() {
// Remove any errors/messages and fade the form.
$(".form_row").removeClass('errors');
$(".form_row_errors").html('');
$("#add_cat").fadeTo('slow', 0.33);
$("#add_cat_btn").attr('disabled', 'disabled');
$("#message").addClass('hide');
});
// Submit the form with ajax.
$("#add_cat").submit(function(){
$.post(
// Grab the action url from the form.
"#add_cat.getAttribute('action')",
// Serialize the form data to send.
$("#add_cat").serialize(),
// Callback function to handle the response from view.
function(resp, testStatus) {
if (resp.error) {
// check for field errors
if (resp.trip_type_error != '') {
$("#trip_type_row").addClass('errors');
$("#trip_type_errors").html(resp.trip_type_error);
}
if (resp.company_name_error != '') {
$("#company_name_row").addClass('errors');
$("#company_name_errors").html(resp.company_name_error);
}
if (resp.individual_name_error != '') {
$("#individual_name_row").addClass('errors');
$("#individual_name_errors").html(resp.individual_name_error);
}
if (resp.phone_error != '') {
$("#phone_row").addClass('errors');
$("#phone_errors").html(resp.phone_error);
}
if (resp.email_error != '') {
$("#email_row").addClass('errors');
$("#email_errors").html(resp.email_error);
}
if (resp.from_country_error != '') {
$("#from_country_row").addClass('errors');
$("#from_country_errors").html(resp.from_country_error);
}
if (resp.to_country_error != '') {
$("#to_country_row").addClass('errors');
$("#to_country_errors").html(resp.to_country_error);
}
if (resp.from_city_error != '') {
$("#from_city_row").addClass('errors');
$("#from_city_errors").html(resp.from_city_error);
}
if (resp.to_city_error != '') {
$("#to_city_row").addClass('errors');
$("#to_city_errors").html(resp.to_city_error);
}
if (resp.departure_date_error != '') {
$("#departure_date_row").addClass('errors');
$("#departure_date_errors").html(resp.departure_date_error);
}
if (resp.return_date_error != '') {
$("#return_date_row").addClass('errors');
$("#return_date_errors").html(resp.return_date_error);
}
if (resp.number_of_passengers_error != '') {
$("#number_of_passengers_row").addClass('errors');
$("#number_of_passengers_errors").html(resp.number_of_passengers_error);
}
$("#add_cat").fadeTo('slow', 1);
$("#add_cat_btn").attr('disabled', false);
} else {
// No errors. Rewrite the category list.
$("#categories").fadeTo('fast', 0);
var text = new String();
for(i=0; i<resp.quotes.length ;i++){
var m = resp.quotes[i]
text += "<li>" + m + "</li>"
}
$("#categories").html(text);
$("#categories").fadeTo('slow', 1);
$("#id_trip_type").attr('value', '');
$("#id_company_name").attr('value', '');
$("#id_individual_name").attr('value', '');
$("#id_phone").attr('value', '');
$("#id_email").attr('value', '');
$("#id_from_country").attr('value', '');
$("#id_to_country").attr('value', '');
$("#id_from_city").attr('value', '');
$("#id_to_city").attr('value', '');
$("#id_departure_date").attr('value', '');
$("#id_return_date").attr('value', '');
$("#id_number_of_passengers").attr('value', '');
}
// Always show the message and re-enable the form.
$("#message").html(resp.message);
$("#message").removeClass('hide');
$("#add_cat").fadeTo('slow', 1);
$("#add_cat_btn").attr('disabled', '');
// Set the Return data type to "json".
}, "json");
return false;
});
});
</script>
<div id="content" class="span9" style="">
<h1>Request Quote</h1>
<div id='message'></div>
<form id='add_cat' method='post' action='.'><input type='hidden' name='csrfmiddlewaretoken' value='KblPqgczzMK7skak162xe4aOL6bLot2A' />
<div class='form_row' id='trip_type_row'>
<div class="span2">
<label for="id_trip_type">Trip type</label>
</div>
<div class="span4">
<select id="id_trip_type" name="trip_type">
<option value="one way" selected="selected">One Way</option>
<option value="round trip">Round Trip</option>
<option value="multi-leg">Multi-Leg</option>
</select>
</div>
<div class="span6">
<p id='trip_type_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='company_name_row'>
<div class="span2">
<label for="id_company_name">Company name</label>
</div>
<div class="span4">
<input id="id_company_name" maxlength="200" name="company_name" type="text" />
</div>
<div class="span6">
<p id='company_name_errors' class="form_row_errors" style="color: red;"></p>
</div>
</div>
<div class='form_row' id='individual_name_row'>
<div class="span2">
<label for="id_individual_name">Individual name</label>
</div>
<div class="span4">
<input id="id_individual_name" maxlength="200" name="individual_name" type="text" />
</div>
<div class="span6">
<p id='individual_name_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='phone_row'>
<div class="span2">
<label for="id_phone">Phone</label>
</div>
<div class="span4">
<input id="id_phone" maxlength="200" name="phone" type="text" />
</div>
<div class="span6">
<p id='phone_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='email_row'>
<div class="span2">
<label for="id_email">Email</label>
</div>
<div class="span4">
<input id="id_email" maxlength="200" name="email" type="text" />
</div>
<div class="span6">
<p id='email_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='from_country_row'>
<div class="span2">
<label for="id_from_country">From country</label>
</div>
<div class="span4">
<input id="id_from_country" maxlength="200" name="from_country" type="text" />
</div>
<div class="span6">
<p id='from_country_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='to_country_row'>
<div class="span2">
<label for="id_to_country">To country</label>
</div>
<div class="span4">
<input id="id_to_country" maxlength="200" name="to_country" type="text" />
</div>
<div class="span6">
<p id='to_country_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='from_city_row'>
<div class="span2">
<label for="id_from_city">From city</label>
</div>
<div class="span4">
<input id="id_from_city" maxlength="200" name="from_city" type="text" />
</div>
<div class="span6">
<p id='from_city_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='to_city_row'>
<div class="span2">
<label for="id_to_city">To city</label>
</div>
<div class="span4">
<input id="id_to_city" maxlength="200" name="to_city" type="text" />
</div>
<div class="span6">
<p id='to_city_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='departure_date_row'>
<div class="span2">
<label for="id_departure_date">Departure date</label>
</div>
<div class="span4">
<input id="id_departure_date" maxlength="200" name="departure_date" type="text" />
</div>
<div class="span6">
<p id='departure_date_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='return_date_row'>
<div class="span2">
<label for="id_return_date">Return date</label>
</div>
<div class="span4">
<input id="id_return_date" maxlength="200" name="return_date" type="text" />
</div>
<div class="span6">
<p id='return_date_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='number_of_passengers_row'>
<div class="span2">
<label for="id_number_of_passengers">Number of passengers</label>
</div>
<div class="span4">
<input id="id_number_of_passengers" maxlength="200" name="number_of_passengers" type="text" />
</div>
<div class="span6">
<p id='number_of_passengers_errors' class="form_row_errors"></p>
</div>
</div>
<input id="add_cat_btn" type='submit' value="save">
</form>
</div><!-- End content -->
Screenshots:
These are images with not functional after Submission Form Submit button but Date Picker
Fields are working becasue Jquery 1.9.1 was used:
Screen 1:
Screen 2:
This is an image with not functional Date Picker because Jquery 1.3.2 was used and Submit
Button is enabled after submision:
Thanks for help.
I managed to solve the problem, the problem was with the newest jquery using different variables. Updated the code above with the answer.
Here is the code:
TEMPLATES:
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
$("#add_cat").ajaxStart(function() {
// Remove any errors/messages and fade the form.
$(".form_row").removeClass("errors");
$(".form_row_errors").html('');
$("#add_cat").fadeTo('slow', 0.33);
$("#add_cat_btn").attr("disabled", "disabled");
$("#message").addClass('hide');
});
// Submit the form with ajax.
$("#add_cat").submit(function(){
$.post(
// Grab the action url from the form.
"#add_cat.getAttribute('action')",
// Serialize the form data to send.
$("#add_cat").serialize(),
// Callback function to handle the response from view.
function(resp, testStatus) {
$(".form_row").removeClass("errors");
$("#trip_type_errors").html("");
$("#company_name_errors").html("");
$("#individual_name_errors").html("");
$("#phone_errors").html("");
$("#email_errors").html("");
$("#from_country_errors").html("");
$("#to_country_errors").html("");
$("#from_city_errors").html("");
$("#to_city_errors").html("");
$("#departure_date_errors").html("");
$("#return_date_errors").html("");
$("#number_of_passengers_errors").html("");
if (resp.error) {
// check for field errors
if (resp.trip_type_error != '') {
$("#trip_type_row").addClass('errors');
$("#trip_type_errors").html(resp.trip_type_error);
}
if (resp.company_name_error != '') {
$("#company_name_row").addClass('errors');
$("#company_name_errors").html(resp.company_name_error);
}
if (resp.individual_name_error != '') {
$("#individual_name_row").addClass('errors');
$("#individual_name_errors").html(resp.individual_name_error);
}
if (resp.phone_error != '') {
$("#phone_row").addClass('errors');
$("#phone_errors").html(resp.phone_error);
}
if (resp.email_error != '') {
$("#email_row").addClass('errors');
$("#email_errors").html(resp.email_error);
}
if (resp.from_country_error != '') {
$("#from_country_row").addClass('errors');
$("#from_country_errors").html(resp.from_country_error);
}
if (resp.to_country_error != '') {
$("#to_country_row").addClass('errors');
$("#to_country_errors").html(resp.to_country_error);
}
if (resp.from_city_error != '') {
$("#from_city_row").addClass('errors');
$("#from_city_errors").html(resp.from_city_error);
}
if (resp.to_city_error != '') {
$("#to_city_row").addClass('errors');
$("#to_city_errors").html(resp.to_city_error);
}
if (resp.departure_date_error != '') {
$("#departure_date_row").addClass('errors');
$("#departure_date_errors").html(resp.departure_date_error);
}
if (resp.return_date_error != '') {
$("#return_date_row").addClass('errors');
$("#return_date_errors").html(resp.return_date_error);
}
if (resp.number_of_passengers_error != '') {
$("#number_of_passengers_row").addClass('errors');
$("#number_of_passengers_errors").html(resp.number_of_passengers_error);
}
} else {
// No errors. Rewrite the category list.
$("#categories").fadeTo('fast', 0);
var text = new String();
for(i=0; i<resp.quotes.length ;i++){
var m = resp.quotes[i]
text += "<li>" + m + "</li>"
}
$("#categories").html(text);
$("#categories").fadeTo('slow', 1);
$("#id_trip_type").val("");
$("#id_company_name").val("");
$("#id_individual_name").val("");
$("#id_phone").val("");
$("#id_email").val("");
$("#id_from_country").val("");
$("#id_to_country").val("");
$("#id_from_city").val("");
$("#id_to_city").val("");
$("#id_departure_date").val("");
$("#id_return_date").val("");
$("#id_number_of_passengers").val("");
}
// Always show the message and re-enable the form.
$("#message").html(resp.message);
$("#message").removeClass('hide');
$("#add_cat").fadeTo('slow', 1);
$("#add_cat_btn").removeAttr("disabled");//attr('disabled', '');
// Set the Return data type to "json".
}, "json");
return false;
});
});
</script>