Autocomplete Address Fill in Django CreateView - django

Ok so I need some help. I am trying to have the address field from my CreateView form auto populate with the Places API result. So I see 2 options:
Override the address field in the CreateView. Use the address input for Places API as the input into the address field for my model.
Autocomplete the address field in the form, from the output of the address input (Places API lookup).
Any suggestions would be greatly appreciated. I have tried multiple different options and cant seem to get it to actually work correctly.
Thanks.
autocomple.html
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search predictions to
// geographical location types.
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'), {types: ['geocode']});
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(['address_component']);
// When the user selects an address from the drop-down, populate the
// address fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
console.log(place)
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details,
// and then fill-in the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle(
{center: geolocation, radius: position.coords.accuracy});
autocomplete.setBounds(circle.getBounds());
});
}
}
views.py
class PropertyCreateView(CreateView):
model = Property
fields = ['address', 'postal_code', 'price',
'details', 'sales_status', 'property_type']
def form_valid(self, form):
return super().form_valid(form)
detail.html
{% load crispy_forms_tags %}
{% block content%}
<div class="container">
<div class="card o-hidden border-0 shadow-lg my-2">
<div class="card-body p-0">
<div class="row">
<div class="col-lg-12">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">New Property</h1>
</div>
<form method="POST">
{% csrf_token %}
<div class="form-group">
<label>Address: </label>
<div id="locationField">
<input id="autocomplete"
placeholder="Enter your address"
onFocus="geolocate()"
type="text"
name="full_address"
class="form-control"
/>
</div>
</div>
<fieldset class="form-group">
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-primary btn-user btn-block"" type="submit">Add Property</button>
</div>
</form>
<hr>
</div>
</div>
</div>
</div>
</div>
</div>
{% include 'properties_app/autocomplete.html' %}

Related

My "cart" cookie in the request passed to my Django view is empty despite it showing in browser storage

I have a store page on my site (written in Django w/ a Passenger server) where users can add products to their shopping cart. The cart is stored as a cookie. When they proceed from the store page to the cart page, the cart view should list all of the items in their cart (which it gets from the cart cookie in the request). This works fine when I run it locally. However, when I run this in production, it almost always says the cart is empty. It only lists the cart items properly if I do a hard refresh of the page.
I've added some print statements to the server, and I can see that the view for the page is being called twice in prod (it's only called once in dev). The first time the view is called, the cart cookie has the correct values. The second time it's called however, the cart cookie in the request is an empty object {}. All other cookies in the request look normal (session id, csrftoken, etc). What's very strange is I can see in the browser's developer panel that the cart cookie is populated in both the request's header cookie tab as well as the storage tab.
Django view/utility functions:
def cart_view(request):
data = cart_data(request)
context = {
'items': data['items'],
'order': data['order'],
'cart_items': data['cart_items'],
}
return render(request, 'store/cart.html', context)
def cart_cookie(request):
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
return cart
def cart_data(request):
cart = cart_cookie(request)
items = []
order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False}
cart_items = order['get_cart_items']
'''
Logic to parse the cart cookie
'''
return {
'items': items,
'order': order,
'cart_items': cart_items,
}
Here's the functions on the store page to populate the cart:
var updateBtns = document.getElementsByClassName('update-cart');
for (var i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function() {
var productId = this.dataset.product;
var action = this.dataset.action;
updateCartCookie(productId, action);
})
}
function updateCartCookie(productId, action) {
if (action == 'add') {
if (cart[productId] === undefined) {
cart[productId] = {'quantity':0};
}
cart[productId]['quantity'] += 1;
} else if (action == 'remove') {
cart[productId]['quantity'] -= 1;
if (cart[productId]['quantity'] <= 0) {
delete cart[productId];
}
}
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/;SameSite=Strict;Secure;";
location.reload();
}
This code is in the page header to initialize the cookies. It's not being called on navigation to the cart page.
<script type="text/javascript">
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++){
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken'); // this is just a string
var cart = JSON.parse(getCookie('cart')); // this is a json object, so we need to parse it
if (cart == undefined) {
cart = {};
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/;SameSite=Strict;Secure;";
}
</script>
And finally, here are the templates for the Store and Cart pages
#Store
{% block content %}
{% load static %}
<div class="container">
<h1 class="page-title">Store</h1>
<div class="row" style="margin-bottom: 20px">
{% for product in products %}
<div class="col-lg-4" style="margin-bottom: 20px">
<img class="thumbnail" src="{{product.imageURL}}">
<br>
<div class="box-element product">
<div>
<h4><strong>{{product.name}}</strong></h4>
<hr>
<p>
{{product.description}}
</p>
</div>
<div style="display: flex; justify-content: space-between; align-items: center;">
<h4>{{ product.price|floatformat:-2 }}</h4>
<button data-product={{product.id}} data-action="add" class="btn light update-cart">Add</button>
</div>
</div>
</div>
{% endfor %}
</div>
<div>
<a style="float: right; margin: 5px;" class="btn dark" href="{% url 'cart' %}">Cart</a>
</div>
</div>
{% endblock content %}
#Cart
{% block content %}
<div class="container">
<h1 class="page-title">Cart</h1>
<div class="">
<a class="btn button light" href="{% url 'store' %}">← Store</a>
<br>
<br>
{% if cart_items == 0 %}
<p style="text-align: center;">Your cart is empty.</p>
{% else %}
<div>
<div class="cart-row">
<div class="shrinking-flex-column-2-1"><strong>Item</strong></div>
<div class="static-flex-column-1"><strong>Price</strong></div>
<div class="static-flex-column-1"><strong>Quantity</strong></div>
<div class="static-flex-column-1"><strong>Total</strong></div>
</div>
{% for item in items %}
<div class="cart-row" style="align-items: center;">
<div class="shrinking-flex-column-2-1">{{item.product.name}}</div>
<div class="static-flex-column-1">${{item.product.price}}</div>
<div class="static-flex-column-1">
<p class="quantity">x{{item.quantity}}</p>
<div class="quantity">
<img class="chg-quantity update-cart" src="{% static 'store/images/arrow-up.png' %}" data-product={{item.product.id}} data-action="add" >
<img class="chg-quantity update-cart" src="{% static 'store/images/arrow-down.png' %}" data-product={{item.product.id}} data-action="remove" >
</div>
</div>
<div class="static-flex-column-1">${{item.get_total}}</div>
</div>
{% endfor %}
<div style="display: flex; justify-content: space-between; align-items: center;">
<div>
<h5>Total Order Items: <strong>{{order.get_cart_items}}</strong></h5>
<h5>Total Order Amount: <strong>${{order.get_cart_total}}</strong></h5>
</div>
<a class="btn dark" role="button" href="{% url 'checkout' %}">Checkout</a>
</div>
</div>
{% endif %}
</div>
</div>
{% endblock content %}
This ended up being entirely a caching issue. Adding the #never_cache decorated to the cart/checkout views fixed the problem.
How to set cache control headers in a Django view class (no-cache)

Populating dropdown in Django using Ajax

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.

Django remove certain parameter from GET

I am doing filter using GET method and I would like to be able to remove only specific filters, how do I do that?
Now I have a form with token fields so I get id's of countries and towns:
<form id="search" method="GET" action="{% url 'selection'%}">
<div class="bg-grey text-center">
<input type="text" class="form-control" id="tokenfield1" name="country">
</div>
{% if filteredcountries %}
<table class="table table-list">
{% for c in filteredcountries %}
<tr>
<td><button type="button" class="btn btn-xs btn-danger" data-remove="{{c.id}}"><i class="fas fa-times"></i></button></td>
<td>{{c.country_name`}}</td>
</tr>
{% endfor %}
</table>
{% endif %}
<div class="bg-grey text-center">
<input type="text" class="form-control" id="tokenfield2" name="town">
</div>
{% if filteredtowns %}
<table class="table table-list">
{% for t in filteredtowns %}
<tr>
<td><button type="button" class="btn btn-xs btn-danger" data-remove="{{t.id}}"><i class="fas fa-times"></i></button></td>
<td>{{t.town_name}}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</form>
views.py:
def hotel_view(request):
countries = request.GET.get('country')
if not countries:
countries = []
else:
countries = countries.split(', ')
towns = request.GET.get('town')
if not towns:
towns = []
else:
towns = towns.split(', ')
results = Hotel.objects.filter(Q(town_id__in = towns) | Q(country_id__in = countries))
context = {
'filteredcountries': countries,
'filteredtowns': towns,
'hotels': results
}
return render(request, 'myapp/hotels.html', context)
Now I want to click the button and remove the specific town or country from the GET and remain the others. Can you lead me to the solution?
example URL before button click:
..myapp/hotels?country=**2**%2C+**4**&town=2
url after button click with country id 2:
..myapp/hotels?country=**4**&town=**2**
or after button click with town id 2:
..myapp/hotels?country=**2**%2C+**4**&town=
This is a solution around using javascript and JQuery. The basic approach is as follows:
Store the current window.location.href in a variable on loading of page. Why?
Otherwise each manipulation of it would result in sending a new GET
request which is probably undesirable
Manipulate the string stored
in the mentioned variable depending on the button clicked.
Preventing the submit button from firing directly but using the
manipulated string
Here the script part with some comments:
<script>
var current_get = window.location.href // Store current url
var handleget = function(part_chooser, id){
// part_chooser = country or town, id = pk to remove
var parts = current_get.split('?');
if (parts.length < 2){ // No get params to manipulate
return;
}
var get_part = parts[1];
var get_parts =get_part.split('&');
var i; // To keep order of new href if important
var str_to_handle; // Part to manipulate
for (i = 0; i < get_parts.length; i++){
if (get_parts[i].startsWith(part_chooser)){
str_to_handle = get_parts[i];
break;
}
};
// Do manipulation and store new url
var get_arr = str_to_handle.split('=');
if (get_arr.length > 0){
params = get_arr[1].split('%2C+');
var index = params.indexOf(id.toString());
if (index >= 0){
params.splice(index, 1);
params = params.join('%2C+');
get_parts[i] = part_chooser + '=' + params;
current_get = parts[0]+'?'+get_parts.join('&');
console.log(current_get);
}
};
};
$('button[type=submit]').click(function(event){
event.preventDefault();
window.location.href = current_get;
})
$('.country-btn').click(function(){
var id = $(this).data('remove');
handleget('country', id);
});
</script>
Some remarks
I intentionally did not use long chains of JS to shorten the code as IMHO it is easier to read step by step
The string manipulation can probably be shortend by clever use of regular expressions.
If your tokenfields contain all the possible ids as a comma seperated list on loading a javascript for deleting the specific id from the tokenfield could look like this:
<script>
$('.country-btn').click(function(){
var id = $(this).data('remove');
var countries = $('#tokenfield1').val().split(',');
var index = countries.indexOf(id.toString());
if (index >= 0){
countries.splice(index, 1)
}
$('#tokenfield1').val(countries.join());
})
</script>
In order to fill your tokenfield with the ids returned in the context you could do something like
<input type="text" class="form-control" id="tokenfield1" name="country"
value="{% for c in filteredcountries %}{{c.id}}{% if not forloop.last %},{% endif %}{% endfor %}">

For loop into js object in template

I want to iterate over an object I return from django view to create dynamically columns in a table (each column is a field in a model and I want to be able to switch the model without changing the template)
In the html body part of the template the same exact code worked fine, in the script section it's not.
My guess is the zip object pass as iterator that can consumed only once? if so how do I make django send a normal list object?
This is my view:
def HelperColumnesFieldsAndNames(data):
columns = { '<ManyToOneRel: client.paymentdata>':["unimp_pay","unimplemented"],
'<ManyToOneRel: client.subscribtiondata>':["subscribtiondata","unimplemented"],
'<ManyToOneRel: client.calldata>':["calldata","unimplemented"],
'<ManyToOneRel: client.extracommunicationdata>':["extracommunicationdata","unimplemented"],
'client.Client.creation_date':["creation_date","Creation Date"],
'client.Client.first_name':["first_name","First Name"],
'client.Client.last_name':["last_name","Last Name"],
'client.Client.address':["address","Address"],
'client.Client.city':["city","City"],
'client.Client.phone_number':["phone_number","Main Phone"],
'client.Client.creator_of_user':["creator_of_user","Client Creator"],
'client.Client.status':["status","Status"],
'client.Client.status_change_time':["status_change_time","Last Time Status Changed"],
'client.Client.allocated':["allocated","Currently Allocated To Talpan"],
'client.Client.group':["group","Owner Group"],
'client.Client.tags':["tags","Tags"],
'client.Client.tagged_items':["tagged_items","Tagged Item"],
}
column_name = []
column_field = []
for field in data:
field = str(field)
if field in columns.keys():
column_field.append(columns[field][0])
column_name.append(columns[field][1])
return zip(column_name, column_field)
# view function
def AllClientts(request):
user_groups = []
for groups in request.user.groups.all():
if groups.name != MANGER_GROUP_NAME:
user_groups.append(groups)
# get all object that belongs to the requested user groups
tableData = Client.objects.filter(group__in=user_groups)
return render(request, "client/clients.html", {"objects": tableData, "columns_name":HelperColumnesFieldsAndNames(Client._meta.get_fields()) })
Working example non in the script section
{% block content %}
<div class="d-flex pt-5 pb-2">
<!-- Need to be set to colums initials names using django -->
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Show
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="swichable_column">
<!--reate fileds name and Showable names -->
{% for name in columns_name %}
<div class="checkbox">
<label>
<input type="checkbox" checked="checked" class="chackable_name" value="{{ name.1 }}">{{ name.0 }}</label>
</div>
{% endfor %}
</div>
</div>
</div>
<div id="example-table"></div>
{% endblock content %}
Script section in my tamplet - not working even do it's the same code
<script>
//define some sample data
var tabledata = [
{id:1, first_name:"Oli Bob", age:"12", col:"red", dob:""},
{id:2, name:"Mary May", age:"1", col:"blue", dob:"14/05/1982"},
{id:3, name:"Christine Lobowski the gratest and latest", age:"42", col:"green", dob:"22/05/1982"},
{id:4, name:"Brendon Philips", age:"125", col:"orange", dob:"01/08/1980"},
{id:5, name:"Margret Marmajuke", age:"16", col:"yellow", dob:"31/01/1999"},
];
$(function() {
var table = new Tabulator("#example-table", {
height:205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
data:tabledata, //assign data to table
layout:"fitColumns",
pagination:"local",
paginationSize:6,
paginationSizeSelector:[3, 6, 8, 10],
columns:[ //Define Table Columns
{% for name in columns_name %}
{title:"{{ name.0 }}", field:"{{ name.1 }}", align:"center", cellClick:function(e, cell){alert("cell clicked - " + cell.getValue())}},
{% endfor %}
]});
</script>
Apparently if I return zip object directly it's itearable and can be consume once only.
I replace zip() with list(zip()) and it's solved that issue

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>