我有一个Django项目,其中一个页面上有一个表格,用户可以在其上输入存款的价值,以及收到存款的日期。
首次加载页面时,将使用从数据库中检索的值填充这些字段。如果用户然后手动更改这些值并刷新页面,则值将恢复为原来的值...我希望表单在任何时候对其值进行任何更改时自动保存,以便在用户更改时值和刷新页面,新值应自动显示。
我该怎么做?
此表单的HTML是:
<form method="POST" enctype="multipart/form-data" data-vat-status="{{project.vat_status}}" data-view-url="{% url 'projects:concept_save_ajax' project.id %}" class="autosave_form full-width">
{% csrf_token %}
<div class="col-12 box">
<div>
<table class="right fixed m-t-md">
<tr>
{% for hidden in deposit_form.hidden_fields %}
{{hidden}}
{% endfor %}
{% for field in deposit_form.visible_fields %}
<td class="p-r-md">{{field.label}}</td><td class="p-r-md">{{field}}</td>
{% endfor %}
<td><a class="email_trigger button" data-view-url="{% url 'comms:open_email_template' project.id %}?template=7">Raise invoice</a></td>
</tr>
</table>
</div>
</div>
<div class="col-6 box">
<div>
<div class="expand-header"><strong class="m-t-md">Costing notes</strong></div>
<table class="vertical-table left">
{% include "projects/includes/stacked_form.html" with form=budget_notes_form %}
</table>
</div>
</div>
<div class="col-6 box">
<div>
<div class="expand-header"><strong class="m-t-md">Project rejected by client?</strong></div>
<table class="vertical-form left">
{% include "projects/includes/stacked_form.html" with form=ended_form %}
</table>
</div>
</div>
</form>
正在调用保存表单的concept_save_ajax
视图在此应用的views.py
文件中定义:
def concept_save_ajax(request, project_id):
""" Save concept forms """
if not request.is_ajax():
raise Http404('Ajax only')
if request.method == 'POST':
project = Project.objects.prefetch_related('budget_versions', 'budget_overview').get(pk=project_id)
form_instances = [
# [DepositForm, project.deposit],
[DepositInfoForm, project.deposit],
[BudgetNotesForm, project.budget_overview],
[EndDetailsForm, project.end],
]
# Save the forms
for form_instance in form_instances:
form = form_instance[0](request.POST, instance=form_instance[1])
if form.is_valid() and form.has_changed():
print form_instance[0], "is valid.", form_instance[0]
updated_details = form.save()
elif form.has_changed():
print form_instance[0], "is not valid", form.errors
return JsonResponse({'error': form.errors})
# url = '/projects/{0}/?tab={1}'.format(project_id, tabs[3])
return JsonResponse({'success': 'Saved'})
else:
raise Http404('Request is not a post')
当我更改显示在其上的任何值时,为什么表单没有保存?如果在更改页面后刷新页面,如何使值保持不变?
修改
forms.py
中定义的表单是:
class DepositInfoForm(ValidatedForm):
amount_exc_vat = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class': 'currency',}),label="Deposit exc VAT")
amount_inc_vat = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class': 'currency', 'readonly':'readonly',}),label="Inc VAT")
date_received = MoonDateField(required=False, label="Date deposit received", widget=forms.DateInput(format='%d/%m/%Y', attrs=({'class':'datepicker'})))
class Meta:
model = Deposit
fields = ('amount_exc_vat', 'amount_inc_vat', 'date_received')#,'received')
def __init__(self, *args, **kwargs):
instance = kwargs.get('instance', {})
project = instance.project
try: amount_exc_vat = int(round(instance.amount_exc_vat))
except TypeError: amount_exc_vat = None
try: amount_inc_vat = int(round(project.deposit.amount_inc_vat))
except TypeError: amount_inc_vat = None
initial = kwargs.get('initial', {})
initial={
'received': project.deposit_received,
'amount_exc_vat': amount_exc_vat,
'amount_inc_vat': amount_inc_vat,
}
kwargs['initial'] = initial
super(DepositInfoForm, self).__init__(*args, **kwargs)
self.fields['date_received'].widget.attrs.update({'data-original-value': self.initial['date_received'] or ''})
def save(self, commit=True):
deposit = self.instance
data = self.cleaned_data
if 'date_received' in self.changed_data:
if not data['date_received'] == '':
deposit.project.deposit_received = True;
self.deposit_r = True
deposit.project.upgrade_detailed_status(Project.ds75)
else:
deposit.project.deposit_received = False;
deposit.project.save()
if ('amount_exc_vat' in self.changed_data or 'date_received' in self.changed_data or 'received' in self.changed_data) and data['amount_exc_vat'] and data['date_received'] and data['received']:
send_message(message_template=2, project=self.instance.project)
self.deposit_r = True
if hasattr(self, 'deposit_r'):
# Make the payment
deposit_payment = Payment(project=deposit.project, is_booking_deposit=True, amount_exc_vat=data['amount_exc_vat'], date_paid=data['date_received'])
return super(DepositInfoForm, self).save(commit=commit)
修改
在我正在处理的页面的HTML文件末尾定义了一些JS函数 - 定义如下(显示我认为我将要使用的那个):
{% block content_scripts %}
<script type="text/javascript" src="{% static 'js/ical_trigger.js' %}"></script>
<script type="text/javascript" src="{% static 'js/email_trigger.js' %}"></script>
<script type="text/javascript">
(function($){ $(document).ready(function(){
$('#id_date_received').on('change', function messageDepositPaid(){
...
})
...
$('.update_presentation').on('click', function updatePresentation(){
var $form = $(this).closest('tbody')
var name = $form.attr('name');
$form.hide();
$('#'+name+' ul').load(location.href + ' #'+name+' ul>*');
})
...
}); })(jQuery)
</script>
(% endblock content_scripts %}
修改
当我检查包含我想要在浏览器中保存的字段的元素时,我可以看到它们位于<table></table>
内的<div></div>
<form></form>
中属性<form method="post" class="autosave_form full-width">
这表明我应该自动保存该表格中的数据......任何人都知道它为什么不存在?