【发布时间】:2021-04-04 10:55:40
【问题描述】:
我一直在尝试在 detailview 中开发一个表单,我做到了。 现在我希望它将数据发送到数据库并在同一页面上显示新数据而无需刷新。
所以我找到了一种无需刷新即可将数据发送到数据库的方法,但是,在不刷新的情况下显示新数据时它不起作用。
我按照本教程进行操作: tutorial from red eye coder club
这是我的代码。
models.py
class ImportantFacts(models.Model):
collection_important_facts = models.ForeignKey(Collection,
related_name="has_important_facts", on_delete=models.CASCADE, null=True)
note = models.TextField(max_length=400, verbose_name='Note')
forms.py
class ImportantFactsForm(forms.ModelForm):
class Meta:
model = ImportantFacts
fields = ['note']
views.py
class CollectionDetail(LoginRequiredMixin, FormMixin, DetailView):
model = Collection
form_class = ImportantFactsForm
template_name = 'taskflow/collection_detail.html'
success_url = None
def get_context_data(self, **kwargs):
context = super(CollectionDetail, self).get_context_data(**kwargs)
context['important_facts'] = ImportantFactsForm()
return context
def post(self, request, *args, **kwargs):
form = ImportantFactsForm(request.POST)
tgt = self.get_object()
if form.is_valid():
new_fact = form.save(commit=False)
new_fact.collection_important_facts = tgt
new_fact.save()
return JsonResponse({'fact': model_to_dict(new_fact)}, status=200)
else:
return redirect('taskflow:collection_all')
facts.js
$(document).ready(function(){
$("createFactForm").click(function() {
var serializedData = $("#createFactForm").serialize();
$.ajax({
url: $("createFactForm").data('url'),
data: serializedData,
type: 'post',
success: function(response) {
$("#canal1").append('<div class="card mb-1"><div class="card-body">' + response.fact.note + '<button type="button" class="close float-right"><span aria-hidden="true">×</span></button></div></div>')
}
})
$("#createFactForm")[0].reset();
});
});
collection_detail.html
<div class="tab-pane active" id="Canal1">
<form class="justify-content-center mx-3" id="createFactForm" method="post" data-url="{% url 'taskflow:collection_detail' pk=object.pk %}">
{% csrf_token %}
<div class="form-group">
{{important_facts.note|as_crispy_field}}
</div>
<button type="button" class="btn btn-outline-success" id="createButton">Enregistrer</button>
</form>
{% if object.has_important_facts %}
{% for fact in object.has_important_facts.all %}
<div class="card mb-1">
<div class="card-body">
{{fact.note}}
<button type="button" class="close float-right">
<span aria-hidden="true">×</span></button>
</div>
</div>
{% endfor %}
{% endif %}
</div>
我想补充一点,我没有完成教程,因为我被困在我应该能够在同一页面上显示新数据而无需刷新的步骤。
非常感谢您的帮助!
编辑 1
在下面的建议之后,这是我在控制台中得到的:
-
添加您的第一个建议代码后:fact: Object { id: 51, collection_important_facts: 52, note: "New test"
-
使用您的第二个建议代码:“Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data”
【问题讨论】: