forms.ValidationError无法正常工作

时间:2010-11-05 17:41:48

标签: django-forms django-views validationerror

我有一个用于上传文件的fileinput字段...视图文件看起来像这样......

from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from forms import RegisterForm
from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
from django import forms
from django.contrib.auth import authenticate
from django.contrib import auth
from settings import MEDIA_ROOT

class UploadFileForm(forms.Form):
    file = forms.Field(widget=forms.FileInput, required=True)

@csrf_protect
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            '''
            just added the late three lines for check
            '''
            username = request.POST['username']
            password = request.POST['password1']
            user = authenticate(username=username, password=password)
            auth.login(request, user)
            request.session['username'] = username
            return HttpResponseRedirect("/file_check/")
    else:
        form = RegisterForm()
    return render_to_response("register.html", RequestContext(request, {'form':form}))

@csrf_protect
def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password1']
        form = UserCreationForm(request.POST)
        user = authenticate(username=username, password=password)
        if user is not None:
            auth.login(request, user)
            request.session['username'] = username
            return HttpResponseRedirect('/file_check/')
    else:
        form = UserCreationForm()
    return render_to_response("login.html", RequestContext(request, {'form':form}))

def logout(request):
    auth.logout(request)
    #del request.session['username']
    return HttpResponseRedirect("/")

@csrf_protect       
def file_check(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/accounts/login/')

    if 'file' in request.FILES:
        file = request.FILES['file']

        if file.content_type != 'application/octet-stream':
            raise forms.ValidationError('File Type Not Supported!!!')

        request.session['contentType'] = file.content_type
        filename = file.name
        fp = open('%s/%s' % (MEDIA_ROOT, filename), 'wb')
        for chunk in file.chunks():
            fp.write(chunk)
        fp.close()
        return HttpResponseRedirect('/result/')
    else:   
        form = UploadFileForm()
        username = request.session['username']
    return render_to_response('file_check.html', RequestContext(request, {'form':form, 'username':username}))

def result(request):
    username = request.session['username']
    content_type = request.session['contentType']
    return render_to_response('result.html', {'username':username, 'content_type':content_type})

然而,当我尝试上传除简单文本文件以外的文件(比如说例如pdf文件)以便检查'/ file_check /'时,我得到的是“ValidationError at / file_check /”。 错误的追溯是

Environment:

Request Method: POST
Request URL: http://localhost:8000/file_check/
Django Version: 1.2.3
Python Version: 2.6.4
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.admin',
 'rocop_web.auth']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  100.                     response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
  76.                     response = view_func(request, *args, **kwargs)
File "/home/kailash/workspace/rocop/rocop_web/../rocop_web/auth/views.py" in file_check
  63.           raise forms.ValidationError('File Type Not Supported!!!')

Exception Type: ValidationError at /file_check/
Exception Value: 

我是django的初学者,发现很难解决。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

from django.forms import forms
from django.db.models.fields.files import FileField

class CustomFileField(FileField):
    attr_class = CustomFieldFile

    allowed_extensions = ('txt', 'pdf')

    def clean(self, value, model_instance):
        extension = str(value).lower().split('.').pop()
        if extension not in self.allowed_extensions:
            raise forms.ValidationError('Only %s are allowed!' % ', '.join(self.allowed_extensions))
        return super(CustomFileField, self).clean(value, model_instance)

你的观点:

@csrf_protect
def file_check(request):
        if request.method == 'POST':
                form = UploadFileForm(data = request.POST, files = request.FILES)
                if form.is_valid():
                        # do stuff!
        else:
                form = UploadFileForm()

并...... “做东西!”应该由扩展FieldFile的CustomFieldFile处理

@edit

  • 使用好的导入类
  • 在编辑中忘记写或丢失,检查是在干净的方法中进行的......