问题描述:

I have a form field like this

class FeedForm(ModelForm):

files=form.FileField(validators=[validate_file_extension])

class Meta:

model=Feed

fields=('text','auth','files',)

with the validator used to allow specific file types:

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.')

I want to raise the above Validation Error in my template,how can I go about it?

views.py that generate form:

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,})

views that the form is on using an include tag:

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 that generates the form: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>

The html that has the above form on using an include tag

{% 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 %}

I have gone through the docs but no breakthrough,Kindly help me out.Thanks in advance

网友答案:

The usual format for a function based view that handles a form is:

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,})

So you just need to change the indentation at the end of the view, so that you return a response for invalid POST requests as well.

Django will automatically display any validation errors if you use {{ form }} in your template. If you render the fields individually, then see the docs for rendering fields manually for how to include errors manually.

相关阅读:
Top