Django模型表单图像字段无法验证

时间:2014-04-01 17:16:55

标签: django django-forms django-file-upload

我正在使用Django Model Form编写一个简单的视图,但是图像字段无法验证'此字段是必需的'错误信息。

我想知道问题出在哪里......

型号:

class Deal(AbstractModel):
    IMAGE_MAX_LENGTH = 200

    place = models.ForeignKey(Place, related_name='deals', related_query_name='deal', verbose_name=_("Place"))
    image = models.ImageField(default='deals/default.png', max_length=IMAGE_MAX_LENGTH, upload_to='deals', verbose_name=_("Image"))
    ...

查看:

@login_required
def deals_create(request):
    # Get place id
    place_id = request.GET.get('place')
    # Get place
    place = Place.objects.get(id=place_id)
    # Process form data
    if request.method == 'POST':
        form = DealsCreateForm(request.POST, request.FILES)
        # Validate post data
        if form.is_valid():
            # Save deal data
            deal = form.save(commit=False)
            deal.place = place
            deal.save()
            # Redirect to reload page and clear post data
            return HttpResponseRedirect(reverse('deal_manager:deals_pending'))
    else:
        form = DealsCreateForm()
    return render(request, 'deal_manager/deals_create.html', {
        'form': form,
        'place': place,
    })

形式:

class DealsCreateForm(ModelForm):

    class Meta:
        model = Deal
        fields = [
            'image', 'product_name', 'product_description',
            'regular_price', 'sale_price', 'limit', 'terms',
        ]

模板:

{% extends "deal_manager/deal_manager.html" %}

{% load i18n %}
{% load staticfiles %}

{% block page_content_body %}
        <div class="row">
            <div class="span12">
                <form action="{% url 'deal_manager:deals_create' %}?place={{ place.id }}" method="post">
                    {% csrf_token %}
                    {{ form.as_p }}
                    <input type="submit" value="{% trans 'Create' %}" />
                </form>
            </div>
        </div>
        <div class="gap gap-small"></div>
{% endblock page_content_body %}

注意:当我从表单元字段中删除图像字段时,表单会生效。

注意:对于此模型,文件上传适用于Django Admin。

1 个答案:

答案 0 :(得分:3)

您需要包含enctype="multipart/form-data"才能将图像字段和文件字段数据绑定到表单。如果没有这些,这些领域将无法验证。

{% block page_content_body %}
        <div class="row">
            <div class="span12">
                <form enctype="multipart/form-data" action="{% url 'deal_manager:deals_create' %}?place={{ place.id }}" method="post">
                    ...

以下是相关文档:https://docs.djangoproject.com/en/stable/ref/forms/api/#binding-uploaded-files-to-a-form