如何为FileField引发验证错误

时间:2016-07-23 17:28:49

标签: django validation

我有一个像这样的表单字段

class FeedForm(ModelForm):
    files=form.FileField(validators=[validate_file_extension])
    class Meta:
        model=Feed
        fields=('text','auth','files',)

使用验证器来允许特定的文件类型: validator.py

def validate_file_extension(value):
    ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
    valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls']
    if not ext.lower() in valid_extensions:
        raise ValidationError(u'Unsupported file extension.')

我想在模板中提出上述验证错误,我该如何解决?

views.py生成表单:

def post_feed(request):
form_class = FeedForm
if request.method == 'POST':
    form = form_class(request.POST,request.FILES)
    if form.is_valid():
        feed = form.save(commit=False)
        feed.user = User.objects.get(pk=7)
        feed.pub_date=timezone.now()
        #instance = Feed(files=request.FILES['files'])
       # feed.files=request.FILES['files']
        feed.save()
        return redirect('home')

else:
    form = form_class()
concern='Concern'
feeds=Feed.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')
paginator = Paginator(feeds,5) # Show 25 contacts per page
page = request.GET.get('page')
try:
    feedz = paginator.page(page)
except PageNotAnInteger:
    feedz = paginator.page(1)
except EmptyPage:
    feedz = paginator.page(paginator.num_pages)

#return redirect('home')
return render_to_response('index.html', {"feeds":feeds,"feedz": feedz,'form':FeedForm(),'feed_detail':feed_detail,})

使用include标记查看表单:

def home(request):
    concern='Concern'
    feeds=Feed.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')
    paginator = Paginator(feeds,5) # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        feedz = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        feedz = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        feedz = paginator.page(paginator.num_pages)
    return render_to_response('index.html', {"feeds":feeds,"feedz": feedz,'form':FeedForm(),'feed_detail':feed_detail,},context_instance=RequestContext(request))

生成表单的html:post_feed.html

<form role="form" action="{% url 'post_feed' %}" enctype="multipart/form-data" method="post">
    {% csrf_token %}
    <div class="mdl-textfield mdl-js-textfield ">
    {{form.text}}
    <label class="mdl-textfield__label" for="{{form.text.id_for_label}}">Cheated on?Blow the whistle here</label>
    </div>
    <div class="mdl-select mdl-js-select mdl-select--floating-label">
     <label class="mdl-select__label" for="{{form.auth.id_for_label}}">Authority addressed to:<br/></label>
    {{form.auth}}

    </div><br/>


      {{form.files}}



   <br/> {{form.files2}}
    <br/>  {{form.files3}}

    <br/><br/>  <button class="mdl-button mdl-js-button  mdl-js-ripple-effect mdl-button--raised mdl-button--colored">Post</button>
    {% if form.errors %}
    {% for field in form %}
    {% for error in field.errors %}
    <div class="alert alert-error">
    <strong>{{error|escape}}</strong>
    </div>
    {% endfor %}
    {% endfor %}
    {% endif %}

    </form>

使用include标记

时具有上述表单的html
{% include "post_feed.html" %}
    <h2>Feed Stream</h2>

    {% for feed in feedz %}
       <strong> {{feed.full_name_of_poster|title}} </strong>  |
            {% if feed.resolved == True %}  
           RESOLVED 
            {% else %}
            UNRESOLVED 
            {% endif %}
           <p> To:<a href="{% url 'authority_details' pk=feed.auth.pk slug=feed.auth.slug %}">{{feed.auth}} </a></p> 

           <p>{{feed.text}} </p>
           <a href="{% url 'feed_detail' slug=feed.slug %}">Full details</a>
          <p id='count'> {{feed.total_concerns}} concern{{feed.total_concerns|pluralize:'s'}} &nbsp {{feed.no_of_comments}} comment{{feed.no_of_comments|pluralize:'s'}} </p>
           <p> {{feed.pub_date|naturaltime|capfirst}} </p>

           <hr/>
           {% endfor %}
<div class="pagination">
    <span class="step-links">
        {% if feedz.has_previous %}
            <a href="?page={{ feedz.previous_page_number }}">previous</a>
        {% endif %}
<span class="current">
            Page {{ feedz.number }} of {{ feedz.paginator.num_pages }}.
        </span>
         {% if feedz.has_next %}
            <a href="?page={{ feedz.next_page_number }}">next</a>
        {% endif %}
    </span>
</div>
{% endblock %}

我已经完成了文档,但没有突破,请帮助我。谢谢提前

1 个答案:

答案 0 :(得分:0)

处理表单的基于函数的视图的通常格式为:

def post_feed(request):
    form_class = FeedForm
    if request.method == 'POST':
        form = form_class(request.POST,request.FILES)
        if form.is_valid():
            # process the form then redirect
            ...
            return redirect('home')
        else:
            # You don't actually need this else statement here
            print form.errors
    else:
        # create blank form for GET requests
        form = form_class()
    # Now return a response for GET requests and invalid POST requests
    concern='Concern'
    feeds=Feed.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')
    return render(request , 'index.html' ,{'feeds':feeds,'form':FeedForm(),'feed_detail':feed_detail,})

因此,您只需要更改视图末尾的缩进,以便为无效的POST请求返回响应。

如果您在模板中使用{{ form }},Django会自动显示任何验证错误。如果单独渲染字段,请手动查看用于渲染字段的文档,以了解如何手动包含错误。