我正在使用modelformset_factory并查看模板中的表单集数据。如果您看下面的图片,模板将在第一张图片中显示数据。但我想像第二张图片一样以相反的顺序查看表单集。首先,我将有新数据输入文本框。然后,旧数据将按照相反的顺序列出,就像在第二张图片中一样。
我的模特是:
class AssistantNotes(BaseModel):
categories = models.CharField(choices=CATEGORIES, max_length=100, verbose_name=_("Kategori"))
dailynote = models.TextField(null=True, blank=True, verbose_name=_("Not Ekle"))
def __unicode__(self):
return "%s / %s" % (self.dailynote, self.categories)
class Meta:
ordering = ['dailynote']
然后我在下面的视图中创建了
。def create_assistant_notes(request):
if request.method == 'GET':
if AssistantNotes.objects.count() == 0:
file_write("get000")
AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('categories', 'dailynote',))
else:
file_write("get111")
AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('categories', 'dailynote',), can_delete=True)
formset = AssistantNotesFormsetFactory(queryset=AssistantNotes.objects.all())
helper = TableInlineHelper()
return render(request, 'create-assistant-notes.html', {'formset': formset, 'helper': helper})
elif request.method == 'POST':
if AssistantNotes.objects.count() == 0:
AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('categories', 'dailynote',))
else:
AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('categories', 'dailynote',), can_delete=True)
formset = AssistantNotesFormsetFactory(request.POST)
if formset.is_valid():
formset.save()
else:
helper = TableInlineHelper()
return render(request, 'create-assistant-notes.html', {'formset': formset, 'helper': helper})
return redirect(reverse('create-assistant-notes'))
我的模板html文件是;
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}{% trans "Notes" %}{% endblock title %}
{% block content %}
<div class="block-area" id="basic">
<form role="form" method="post">
{% crispy formset helper %}
<div class="modal-footer">
<button type="submit" class="btn btn-sm btn-alt">{% trans "Save" %}</button>
<button type="button" class="btn btn-sm btn-alt" data-dismiss="modal">{% trans "Cancel" %}</button>
</div>
</form>
</div>
{% endblock content %}