1

我正在使用 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。

4

1 回答 1

4

您需要包含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

于 2014-04-01T18:16:29.473 回答