如何修复从Django的引导模态形式上传图像

时间:2019-06-17 18:31:24

标签: python django ajax twitter-bootstrap-3

我找不到有关如何通过Django模式形式加载图像的信息。如何通过Django模式表格上传文件?

我的文件models.py

class Meal(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    name = models.CharField(max_length=500)
    short_description = models.CharField(max_length=500)
    image = models.ImageField(upload_to='meal_images/', blank=False)
    price = models.IntegerField(default=0)

    def __str__(self):
        return self.name

我的文件form.py

class MealForm(forms.ModelForm):
    class Meta:
        model = Meal
        exclude = ("restaurant",)

需要添加哪些内容到views.py以处理图像加载 views.py

def restaurant_add_meal(request):
    data = dict()
    if request.method == "POST":
        form = MealForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            meals = Meal.objects.all()
            data['meal_list'] = render_to_string('meal_list.html',{'meals':meals})
        else:
            data['form_is_valid'] = False
    else:
        form = MealForm()
    context = {
    'form': form
    }
    data['html_form'] = render_to_string('restaurant/add_meal.html', context, request=request)
    return JsonResponse(data)

表格形式add_meal.html

{% load crispy_forms_tags %}

<form method="POST" data-url="{% url 'restaurant-add-meal' %}" class="create-form" enctype="multipart/form-data">
    {% csrf_token %}
        <div class="modal-header bg-blue">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true" class="text-white">&times;</span>
            </button>
        <h4 class="modal-title text-center text-white" >Add Meal</h4>
        </div>
        <div class="modal-body">
        {{form|crispy}}
        </div>
        <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-pink">Add Meal</button>
        </div>
</form>

处理表单的ajax代码。我不明白这里缺少什么。

plugin.js

$(document).ready(function(){
    $('.show-form').click(function(){
        $.ajax({
            url: '/restaurant/meal/add',
            type: 'get',
            dataType:'json',
            beforeSend: function(){
                $('#modal-meal').modal('show');
            },
            success: function(data){
                $('#modal-meal .modal-content').html(data.html_form);
            }
        })
    })
    $('#modal-meal').on('submit','.create-form' , function(){
        var form = $(this);
        $.ajax({
            url: form.attr('data-url'),
            data: form.serialize(),
            type: form.attr('method'),
            dataType: 'json',
            success: function(data){
                if(data.form_is_valid){
                    $('#meal-table tbody').html(data.meal_list);
                $('#modal-meal').modal('hide');
            } else {
                $('#modal-meal .modal-content').html(data.html_form)
            }
        }
        })
        return false;
    })
    });

1 个答案:

答案 0 :(得分:0)

我不知道django,所以我无法提供服务器端代码,但是ajax需要使用FormData对象来上传图像文件。

$('#modal-meal').on('submit','.create-form' , function(){
    var form = $(this);
    var fd = new FormData(this);
    $.ajax({
        url: form.attr('data-url'),
        data: fd,
        type: form.attr('method'),
        dataType: 'json',
        processData: false,
        contentType: false,
        success: function(data){
            if(data.form_is_valid){
                $('#meal-table tbody').html(data.meal_list);
            $('#modal-meal').modal('hide');
        } else {
            $('#modal-meal .modal-content').html(data.html_form)
        }
    }
    })
    return false;
})