【问题标题】:Add django form without refreshing the page using ajax使用ajax添加django表单而不刷新页面
【发布时间】:2019-10-21 14:44:08
【问题描述】:

我正在尝试实现一个 django 模型表单,以使用 html 模式弹出添加产品表单将新项目添加到类别表中,并且代码工作正常。在这里,我希望模型表单能够异步工作,而无需使用 javascript(ajax) 刷新页面。

提交 ajax_form 后数据填充到 db_table 中,但在我刷新页面之前它不会显示在 html 模板中。我该怎么做?

models.py

class Category(models.Model):
    title = models.CharField(max_length=250)

class Product(models.Model):
    name = models.CharField(max_length=250)
    category = models.ForeignKey(Category,on_delete=models.CASCADE)
    cost_price = models.FloatField()
    sell_price = models.FloatField()
    quantity = models.IntegerField()

forms.py

class AddProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'
class AddCategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = '__all__'

views.py

def add_product(request):
    categories = Category.objects.all()

    if request.method == 'POST':
        product_form = AddProductForm(request.POST or None)

        if product_form.is_valid():
            product = product_form.save(commit=False)
            product.save()

            return redirect('add_product')
        else:
            return HttpResponse(product_form.errors)
    else:
        product_form = AddProductForm()
    return render(request,'add_product.html',{'product_form':product_form, 'categories':categories})

def ajax_add_category(request):
    if request.method == 'POST':
        category_form = AddCategoryForm(request.POST or None)
        if category_form.is_valid():
            category = category_form.save(commit=False)
            category.save()
            return redirect('add_product')
    else:
        category_form = AddCategoryForm()
    return render(request,'add_product.html',{'form':category_form})

html模板

    <label>Product Name</label>
    <input type="text" name="name" class="form-control" placeholder="Item Name..." maxlength="200" required id="id">
    <label>Category</label>
    <div class="form-group">
                 <select name="category" class="form-control mr-3" style="width:50%; display:inline;" required id="id_category">
{% for category in categories %}


<option value="{{category.id}}">{{category.title}}</option>
  {% endfor %}

添加新类别

html 模态

<div class="modal" id="item-category-modal">
 <div class="modal-body">
  <form method="POST" data-url="{% url 'add-category' %}" id="category-ajax-form">
    {% csrf_token %}
  <p><label for="id_title">Title:</label> <input type="text" name="title"></p>
 <button class="btn btn-primary mt-30">Add Category</button>
  </form>
 </div>
 </div>

javascript(ajax) 代码

<script type='text/javascript'>
  $(document).ready(function(){
    var $categoryForm = $('#category-ajax-form')
    $categoryForm.submit(function(event){
      event.preventDefault()
      event.stopPropagation()
      var $formData = $(this).serialize()
var $thisURL = $categoryForm.attr('data-url') 
$.ajax({
method: "POST",
url: $thisURL,
data: $formData,
success: handleFormSuccess,
});
});

    function handleFormSuccess(data, textStatus, jqXHR){
      $("#id_category").append(new Option(data.title, data.pk));

      $('#id_category').val(data.pk);
      $('#item-category-modal').modal('toggle');

// $categoryForm.reset(); // reset form data
}
});
</script>

urls.py

urlpatterns = [
path('add-category/', views.ajax_add_category, name='add-category'),
path('add/product/',views.add_product,name='add_product'),
    ]

【问题讨论】:

  • 请检查浏览器控制台中的错误。
  • 控制台中没有错误,并且数据也填充到 db_table 中。但是只有在模板中刷新页面时才会显示数据。
  • 能否分享您的 urls.py 文件。
  • @chiragsoni 已编辑
  • 所以基本上新类别在通过 ajax 添加一个类别后并没有显示在类别列表中,而是在 db 中填充,对吗?

标签: ajax django django-forms


【解决方案1】:

首先你创建一个新的 html 模板让我们说ajaxCategories.html 并在其中添加这个代码:

{% for category in categories %}
<option value="{{category.id}}">{{category.title}}</option>
{% endfor %}

现在在您现有的 html 模板中删除此代码并像这样包含它:

<select name="category" class="form-control mr-3" style="width:50%; display:inline;" 
   required id="id_category">
 {% include "ajaxCategories.html" %}
</select>

注意:如果包含使用正确的路径,那么只会包含它。

现在在 ajax 视图中进行如下更改:

def ajax_add_category(request):
    if request.method == 'POST':
        category_form = AddCategoryForm(request.POST or None)
        if category_form.is_valid():
            category = category_form.save(commit=False)
            category.save()
            #return redirect('add_product')
            categories = Category.objects.all()
    else:
        category_form = AddCategoryForm()
    return render(request,'ajaxCategories.html',{'categories':categories})

现在在handleFormSuccessfn 中添加这行代码:

$("#id_category").html(data)

通过这个新实现,您在 ajax 响应中获得的 data 是您将适合 select 标记的整个 html 模板。

【讨论】:

  • 欢迎提出任何问题。
  • 知道你需要做哪些改变吗?
  • 不要通过回答来吹嘘,而是要获得好的结果,养成欣赏回答你问题的人的习惯,即使你从他们那里得到了一点想法。它只对你有益。
  • 对不起兄弟没有足够的声誉
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 2020-10-13
  • 2021-05-15
  • 1970-01-01
  • 2017-04-09
相关资源
最近更新 更多