Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3875742
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T22:18:07+00:00 2026-05-19T22:18:07+00:00

i have a fileinput field for uploading files … the view file looks like

  • 0

i have a fileinput field for uploading files … the view file looks like this …

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

However, when i try to upload the file other than simple text file (say for e.g. pdf files) for checking at ‘/file_check/’ all i get is “ValidationError at /file_check/”.
The traceback of the error is

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: 

I am a beginer in django and finding it hard to solve. Your help is warmly appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T22:18:08+00:00Added an answer on May 19, 2026 at 10:18 pm
    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)
    

    your view:

    @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()
    

    And …
    “do stuff!” should be handled by a CustomFieldFile that extends FieldFile

    @edit

    • use the good import class
    • Forgot to write or was lost in edit, that the check is made in the clean method …
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Im trying to make a file input field have the following extensions only .zip,
I have a file input field with opacity: 0; and filter: alpha(opacity: 0); that
I have an admin module, that has a file input filed, where I'd like
I have a file input element that needs to be cloned after the user
Have you managed to get Aptana Studio debugging to work? I tried following this,
I have a form in ColdFusion that initially has 5 input fields for file
I'm trying to make a webpage that allows the uploading of multiple files at
i'm uploading a 70mb ZIP file . perhaps debugging may be putting things out
I am trying to attach a file with a contact form. My code looks
I'm making an app that has a file name field, an upload file field

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.