html Django Admin:使用AJAX保存 - 覆盖`admin / change_form.html`模板

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html Django Admin:使用AJAX保存 - 覆盖`admin / change_form.html`模板相关的知识,希望对你有一定的参考价值。

{% extends "suit:admin/change_form.html" %}


{% block extrajs %}
	{{ block.super }}

	<script type="text/javascript">
		$(document).ready(function() {
			jQuery.fn.filterFind = function(selector) { 
				return this.find('*')			// Take the current selection and find all descendants,
							.addBack()			// add the original selection back to the set 
							.filter(selector);	// and filter by the selector.
			};

			/* */
			$(document).on('click', '#{{ opts.module_name }}_form .js-submit-with-ajax', function(e) {
				e.preventDefault();

				var $self = $(this);
				var $thisForm = $self.parents('form:first');
				var formData = $thisForm.serializeArray();
				//formData[$self.attr('name')] = $self.attr('value');
				formData.push({name: $self.attr('name'), value: $self.attr('value')});

				var serializedFormData = "";
				$.each(formData, function(index, entry) {
					serializedFormData += entry.name + "=" + entry.value + "&";
				});
				//console.log(serializedFormData);

				// Add a nice "Loading... message to the button when we start the ajax"
				$(this).append('<br />Loading...');


				var scrollLookupTable = {
					'body': $('body').scrollTop()
				};
				$thisForm.filterFind(':input').each(function(index) {
					// Disable the field while we are saving
					$(this).attr('disabled','disabled');

					// Put the scrollTop into our lookup table
					var id = $(this).attr('id');
					if(id && id.length > 0)
					{
						scrollLookupTable['#' + id] = $(this).scrollTop();
					}
				});

				$.ajax({
					type: "POST",
					url: '{{ request.build_absolute_uri }}',
					data: serializedFormData // serializes the form's elements.
				}).done(function(data) {
					var $html = $(data);
					var $newFormInsides = $html.find('#{{ opts.module_name }}_form').children();
					// Update the form with the new stuff
					$thisForm.html($newFormInsides);

					// Set the scrolls to the same position
					$.each(scrollLookupTable, function(index, value) {
						//console.log(index + " : " + value);
						$(index).scrollTop(value);
					});
				});
			});
			/* */
		});
	</script>

{% endblock %}


{% block submit_buttons_bottom %}
	{{ block.super }}

	<button type="button" name="_continue" value="true" class="btn js-submit-with-ajax">Save (with AJAX)</button>
{% endblock %}

以上是关于html Django Admin:使用AJAX保存 - 覆盖`admin / change_form.html`模板的主要内容,如果未能解决你的问题,请参考以下文章

AJAX向Django后端提交POST请求

django - 继承 AbstractUser 明文 问题处理

django的views直接传一段html代码调用模板中的js函数。

django模板中使用JQ代码实现瀑布流显示效果

ajax向Django前后端提交请求和CSRF跨站请求伪造

Django:在 django admin 中扩展 base.html