Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing a Django model with a filefield without re-uploading the file

Below is a simplified version of the django code in my project; it allows users to upload a file and give it a title. This feature works perfectly. However, when user goes re-edit the form later, the file and title are redisplayed, but when the user goes to submit the file filed empties. The file field of the form reopened for editing looks like this:

Currently: media_location/uploadedfile.mp3

Change: [Choose File] No file Chosen

And after I submit it, it's:

  • This Filed is required

[Choose File] No file Chosen

How do I get it so that the user does not have to reupload the file? It does not matter to me whether the field is made readonly once submission is done, or whether it remains editable. The finished project is not for a client and will only be available to a small group of trusted users, but I would still like to follow best practices if possible. Thanks for any help.

Django Code:

models.py

class Recording(models.Model):
    rec_title=models.CharField(max_length=200,blank=True)
    rec_file = models.FileField(upload_to='recordings')

forms.py

from django import forms 
from songstorage.models import Recording
class RecordingForm(forms.ModelForm):
    rec_file=forms.FileField(label='Upload File')
    rec_title=forms.CharField(label='Recording Title',required=False)       
    class Meta:
        model=Recording

views.py

def addrecordings(request,recordingfile):
    #if there is a recordingfile in the url, the user is editing...
    if recordingfile:
        recording=Recording.objects.get(rec_title=recordingfile)
        recording_form = RecordingForm(instance=recording)
    #...Otherwise a new form is createing a new one
    else:
        recording_form = RecordingForm(request.POST, request.FILES)

    #When the form is submitted, do the following:
    if request.method == 'POST': 
        #check if its valid
        if recording_form.is_valid():
            recording_form.save() 
            #if sucessfully submitted, redirect
            return redirect('/recordings/')
    return render_to_response('addrecordings.html',{'recording_form':recording_form},context_instance=RequestContext(request))
like image 268
sean Avatar asked Jul 21 '13 16:07

sean


People also ask

Where does Django store files?

By default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you're using these defaults. However, Django provides ways to write custom file storage systems that allow you to completely customize where and how Django stores files.

What is request files in Django?

A view handling this form will receive the file data in request. FILES , which is a dictionary containing a key for each FileField (or ImageField , or other FileField subclass) in the form. So the data from the above form would be accessible as request. FILES['file'] . Note that request.


1 Answers

I had the same problem.

You can override a model's default clean function. This validates all forms, the user can change the image file on edit, and the file is guaranteed to be nonempty.

class MyModel(models.Model):
  image = models.ImageField(blank=True)
  def clean(self, *args, **kwargs):
    super(MyModel, self).clean(*args, **kwargs)
    if not self.image:
      raise ValidationError('Please provide an image')
like image 119
Liu Avatar answered Sep 22 '22 19:09

Liu