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

  • Home
  • SEARCH
  • 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 7668953
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T15:29:13+00:00 2026-05-31T15:29:13+00:00

The problem Add custom validation to a form field in Django 1.3, the form

  • 0

The problem

Add custom validation to a form field in Django 1.3, the form is created by the generic view CreateView.

The model

class Picture(models.Model):
    file = models.ImageField(upload_to=get_image_path)
    filename = models.CharField(max_length=50, blank=True)
    user = models.ForeignKey(User, editable=False)
    upload_date = models.DateTimeField(auto_now_add=True,editable=False)

Generic view CreateView, a bit modified

class PictureCreateView(CreateView):
    model = Picture

    def clean_file(self,form):
        if image:
            if image._size > settings.MAX_IMAGE_SIZE:
                raise ValidationError("Image file too large ( > 20mb )")
        else:
             raise ValidationError("Couldn't read uploaded image")

    def get_form(self, form_class):
        form = super(PictureCreateView, self).get_form(form_class)
        form.instance.user = self.request.user
        return form

    def form_invalid(self, form):
        ...omitted none important code...
        response = JSONResponse(data, {}, response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response

    # Called when we're sure all fields in the form are valid
    def form_valid(self, form):
        ...omitted none important code...
        response = JSONResponse(data, {}, response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response

My question is: How can I do custom validation on the file field, before form_valid() is reached?

In short, what I’ve done so far

According to the documentation here – https://docs.djangoproject.com/en/dev/ref/forms/validation/
I should be able to override the file fields form validator, which I’m trying to do with clean_file()
“The clean_() method in a form subclass – where is replaced with the name of the form field attribute. ”
This would have been easy if I had created the form manually, but it’s created by Django from the model by the generic view.

My current solution, which is a ugly hack:
You can see that I’ve overridden form_valid() and form_invalid(), in form_valid() I now call clean_file()
and if it’s a error I call form_invalid(). This creates a few problems, for example I need to create the error message response manually.

  • 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-31T15:29:14+00:00Added an answer on May 31, 2026 at 3:29 pm

    Why not create your modelform ?

    from django import forms
    
    class PictureForm(forms.ModelForm):
        def clean_file(self,form):
            if image:
                if image._size > settings.MAX_IMAGE_SIZE:
                    raise ValidationError("Image file too large ( > 20mb )")
            else:
                raise ValidationError("Couldn't read uploaded image")
    
        class Meta:
            model = Picture
    

    Then you could use it in your view with the form_class attribute:

    class PictureCreateView(CreateView):
        form_class = PictureForm
    
        # .... snip
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have created a custom validation rule (uniqueUserName). The problem I'm having is that
I have a very basic entity model which I'm trying to add custom validation
I am using the Jquery Validation plug-in, however i need to add a custom
I have created a custom configuration section in a c# class library by inheriting
Been trying to add custom post type which was successful the problem i am
I have a custom DataAnnotationsModelValidatorProvider for doing model validation in a more dynamic way
I've created a custom validator to validate dateTimefield. My problem is that I can't
The problem Dynamically add and remove fields to entities on the fly using Hibernate.
I have a problem: I've add a Jquery UI drag-n-drop widget to my page,
There are a set of point that are collinear. The problem is to add

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.