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 8520111
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T06:26:38+00:00 2026-06-11T06:26:38+00:00

I have a form in my html page, that prompts user to upload File

  • 0

I have a form in my html page, that prompts user to upload File or Image to the server. I want to be able to upload ether file or image. Let’s say if user choose file, image should be null, and vice verso. Right now I can only upload both of them, without error. But If I choose to upload only one of them (let’s say I choose image) I will get an error:

"Key 'attachment' not found in <MultiValueDict: {u'image': [<InMemoryUploadedFile: police.jpg (image/jpeg)>]}>"

enter image description here

models.py:

#Description of the file 
class FileDescription(models.Model):

    TYPE_CHOICES = (
        ('homework', 'Homework'),
        ('class', 'Class Papers'),
        ('random', 'Random Papers')                    
    )

    subject = models.ForeignKey('Subjects', null=True, blank=True)
    subject_name = models.CharField(max_length=100, unique=False)

    category = models.CharField(max_length=100, unique=False, blank=True, null=True)

    file_type = models.CharField(max_length=100, choices=TYPE_CHOICES, unique=False) 
    file_uploaded_by = models.CharField(max_length=100, unique=False)
    file_name = models.CharField(max_length=100, unique=False)
    file_description = models.TextField(unique=False, blank=True, null=True)
    file_creation_time = models.DateTimeField(editable=False)
    file_modified_time = models.DateTimeField()

    attachment = models.FileField(upload_to='files', blank=True, null=True, max_length=255)
    image = models.ImageField(upload_to='files', blank=True, null=True, max_length=255)

    def __unicode__(self):
        return u'%s' % (self.file_name)

    def get_fields(self):
        return [(field, field.value_to_string(self)) for field in FileDescription._meta.fields]

    def filename(self):
        return os.path.basename(self.image.name)

    def category_update(self):
        category = self.file_name
        return category

    def save(self, *args, **kwargs):
        if self.category is None:
            self.category = FileDescription.category_update(self)
        for field in self._meta.fields:
            if field.name == 'image' or field.name == 'attachment':
                field.upload_to = 'files/%s/%s/' % (self.file_uploaded_by, self.file_type)
        if not self.id:
            self.file_creation_time = datetime.now()
        self.file_modified_time = datetime.now()
        super(FileDescription, self).save(*args, **kwargs)

forms.py

class ContentForm(forms.ModelForm):
    file_name =forms.CharField(max_length=255, widget=forms.TextInput(attrs={'size':20}))
    file_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':25}))

    class Meta:
        model = FileDescription 
        exclude = ('subject',
                   'subject_name',
                   'file_uploaded_by',
                   'file_creation_time',
                   'file_modified_time',
                   'vote')

    def clean_file_name(self):
        name = self.cleaned_data['file_name']
        # check the length of the file name
        if len(name) < 2:
            raise forms.ValidationError('File name is too short')
        # check if file with same name is already exists
        if FileDescription.objects.filter(file_name = name).exists():
            raise forms.ValidationError('File with this name already exists')
        else:
            return name

views.py

if request.method == "POST":
        if "upload-b" in request.POST:
            form = ContentForm(request.POST, request.FILES, instance=subject_id)       
            if form.is_valid(): # need to add some clean functions
               # handle_uploaded_file(request.FILES['attachment'],
               #                      request.user.username,
               #                      request.POST['file_type'])
                form.save()
                up_f = FileDescription.objects.get_or_create(
                    subject=subject_id,
                    subject_name=subject_name,
                    category = request.POST['category'],
                    file_type=request.POST['file_type'],
                    file_uploaded_by = username,
                    file_name=form.cleaned_data['file_name'],
                    file_description=request.POST['file_description'],
                    image = request.FILES['image'],
                    attachment = request.FILES['attachment'],
                )
                return HttpResponseRedirect(".")
  • 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-06-11T06:26:39+00:00Added an answer on June 11, 2026 at 6:26 am

    Let’s say if user choose file, image should be null, and vice verso.

    You could:

    1. make an SQL constraint,

    2. override model.save() to fail if either file or image is blank,

    3. define ContentForm.clean() to raise a ValidationError if either file or image is blank, see Cleaning and validating fields that depend on each other.

    Also be careful that up_f will be a tuple in:

    up_f = FileDescription.objects.get_or_create(
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

So I have a form on PHP/HTML page. User submitss it to that same
I have a form on an HTML page that a user needs to use
All, I have an HTML page that contains a form. When the user completes
Ok, So I have a form that is on page 'index.html'. The user submits
I have a form that I don't render as part of HTML page but
I have a html form that posts to a new page on submit. If
I have an HTML page with a simple form. When the user clicks submit,
I have an HTML form that calls an ASP.NET page when a button is
I have a html page that looks like: <html> .. <form post=/products.hmlt ..> ..
So I have a html page that has a form, and a table inside

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.