我有一个简单ModelForm
的页面加载后提交表单。我需要表单在加载时停止提交,以便我可以正确地将模板值传递给它。
关于如何阻止页面在加载时提交的任何想法?
下面是有问题的代码。
页面 HTML:
{% extends "stamped/home.html" %}
{% block results %}
<h2>Let The world know what you think!</h2>
<form enctype="multipart/form-data" method="post" action="">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input id="upload_submit" type="submit" value="Stamp it!">
</form>
{% endblock %}
Django视图:
@login_required
def make_comment(request):
if request.method == 'POST':
print request.POST
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.save()
# render?
return HttpResponseRedirect('/results/', {
'restaurant': get_object_or_404(
Restaurant,
name=request.POST['name'],
address=request.POST['address']
)
})
else:
form = CommentForm()
return render(request, 'stamped/comment.html', {'form': form}
)
HTML 模板正在扩展:
<!DOCTYPE html>
<!-- stamped home page -->
<html>
<head>
<title>Stamped</title>
<link type="text/css" href="{{ STATIC_URL }}css/style.css" rel="stylesheet">
</head>
<body>
{% csrf_token %}
<div id="navi">
<div id="navi_elements">
<ul>
<li class="navi_text"><a href="{% url 'home' %}">Stamped Home</a></li>
{% if user.is_authenticated %}
<li class="navi_text"><a href="{% url 'logout_view' %}">Logout</a></li>
{% else %}
<li class="navi_text"><a href="{% url 'django.contrib.auth.views.login' %}">Login</a></li>
{% endif %}
</ul>
</div>
</div>
<div id="panel">
<input id="searchTextField" type="text" size="50">
</div>
<div id="map-canvas"></div>
<div id="results">{% block results %}{% endblock %}</div>
{% if top_choices %}
<div id='feed_stream'>
{% for r in top_choices %}
<div class='top_choice_div'>
<ul class='top_choice_list'>
{% for i in r %}
{% if forloop.first %}
<li class="choice_cat_name"> {{ i.category }}</li>
{% endif %}
<li>{{ i.name }} Rating: {{ i.rating }}</li>
{% endfor %}
</ul>
</div>
{% endfor %}
<div id='recently_added_Restaurants'>
<ul id='rar_list'>
{% for i in recently_added_Restaurants %}
{% if forloop.first %}
<li id="rar_name">Recently Added Restaurants</li>
{% endif %}
<li>{{ i.name }} Rating: {{ i.rating }}</li>
{% endfor %}
</ul>
</div>
<div id='recent_reviews'>
<ul id='rr_list'>
{% for i in recent_reviews %}
{% if forloop.first %}
<li id="rr_name">Recent Reviews</li>
{% endif %}
<li>{{ i.restaurant }} Rating: {{ i.rating }}</li>
{% endfor %}
</ul>
</div>
</div>
{% endif %}
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script language="JavaScript" type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script language="JavaScript" type="text/javascript" src="{{ STATIC_URL }}js/map.js"></script>
<script language="JavaScript" type="text/javascript" src="{{ STATIC_URL }}js/home_jquery.js"></script>
<script language="JavaScript" type="text/javascript" src="{{ STATIC_URL }}js/jquery_cookie/jquery.cookie.js"></script>
</html>
JS:
home_jq.js:
$(document).ready(function(){
//initialize main map
$(google.maps.event.addDomListener(window, 'load', initialize));
$(".top_choice_list").selectable();
});
地图.js:
//intialize main map
function initialize() {
var mapOptions = {
//set lat long for nyc
center: new google.maps.LatLng(40.7200, -73.9900),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(40.7200, -74.0000),
new google.maps.LatLng(40.7200, -73.9000));
var options = {
bounds: defaultBounds,
types: ['establishment'],
//rescrict results to US
componentRestrictions: {country: 'US'}
};
var input = (document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
//remove any pervious info on the map (if there is any) to get ready for a new query
infowindow.close();
marker.setVisible(false);
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** @type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
//var output_list = [place.name, address];
//handle CSRF
//send map change to home_jQuery.js
/* var csrftoken = $.cookie('csrftoken');
var send_data = { 'name': place.name, 'address': address};
$.post( '/results/', send_data, function (response){
alert(response);
return send_data;
} );*/
var send_data = { 'name': place.name, 'address': address};
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({ url: '/results/',
type: 'POST',
data: send_data,
success: function(response) {
console.log("everything worked!");
$("#results").html(response);
},
error: function(obj, status, err) { alert(err); console.log(err); }
});
});
}