【问题标题】:Django Form Ajax no refreshDjango Form Ajax 没有刷新
【发布时间】: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">&times;</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">&times;</span></button>
            </div>
          </div>


        {% endfor %}
       {% endif %}

     </div>

我想补充一点,我没有完成教程,因为我被困在我应该能够在同一页面上显示新数据而无需刷新的步骤。

非常感谢您的帮助!

编辑 1

在下面的建议之后,这是我在控制台中得到的:

  1. 添加您的第一个建议代码后:fact: Object { id: 51, collection_important_facts: 52, note: "New test"

  2. 使用您的第二个建议代码:“Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data”

【问题讨论】:

    标签: python django ajax forms


    【解决方案1】:

    您能否在您的控制台上分享请求的输出?

    先试试吧:

    $.ajax({
            url: $("createFactForm").data('url'),
            data: serializedData,
            type: 'post',
            success: function(response) {
              console.log(response)
            }
        })
    

    可能和响应的格式有关,如果是这种情况,你应该试试:

    $.ajax({
            url: $("createFactForm").data('url'),
            data: serializedData,
            type: 'post',
            success: function(response) {
              var resp = JSON.parse(response);
              console.log(resp)
            }
        })
    

    让我们看看会发生什么..

    【讨论】:

    • 感谢您的帮助。所以我尝试了你的建议,结果如下:1)在添加你的第一个建议代码后:fact:Object { id:51,collection_important_facts:52,注意:“新测试”2)使用你的第二个建议代码:“Uncaught SyntaxError :JSON.parse:JSON 数据的第 1 行第 2 列出现意外字符“谢谢!
    • 所以,看起来您的代码运行良好,不需要更多解析,...您只需将 json“响应”作为普通 json 对象访问
    • 感谢您的回答。但是我认为我的代码中的 Jason 对象是用 « response.fact.note » 呈现的,所以我做错了什么?你会怎么做?再次感谢。
    • 解决方案:只需将 #canal1 更改为 #Canal1..... 24 小时即可解决这个简单的语法错误。还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2013-08-27
    相关资源
    最近更新 更多