Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "This field is required" even though file is uploaded

I'm new at Django and trying a simple form. I have a model class "Profile" with a file field (schema_file) defined and also a ModelForm class for it. When I try to create a new profile in the browser I get an error "This field is required" on the schema_file field even though i chose a file in the file chooser, any ideas? my classes below:

class Profile(models.Model):
    class Meta:
        db_table = 'target_profiles'

    class SchemaType:
        XML = 1
        CSV = 2
        XLS = 3
        JSON = 4
        DB = 5
        SCHEMA_CHOICES = (
                          (XML, 'XML'),
                          (CSV, 'CSV'),
                          (XLS, 'Excel'),
                          (JSON, 'JSON'),
                          (DB, 'Database'),
                          )

    name = models.CharField(max_length=32, unique=True)
    description = models.CharField(max_length=128, null=True, blank=True)
    schema_type = models.IntegerField(choices=SchemaType.SCHEMA_CHOICES, default=SchemaType.CSV)
    schema_file = models.FileField(upload_to='schema_files', max_length=64)


    def __unicode__(self):
        return self.name

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile

view:

def add_profile(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES)
        if form.is_valid():
            cd = form.cleaned_data
            return HttpResponseRedirect('/profiles')
    else:
        form = ProfileForm()
    return render(request, 'profiles/add_profile.html', {'form': form})
like image 702
michalv82 Avatar asked May 12 '13 15:05

michalv82


2 Answers

As you haven't posted your view, I can only guess its because you forgot to include request.FILES:

form = ProfileForm(request.POST, request.FILES)

And perhaps forgot to add enctype=multipart/form-data to your form.

like image 183
Burhan Khalid Avatar answered Nov 10 '22 02:11

Burhan Khalid


Add enctype="multipart/form-data"

<form enctype="multipart/form-data" method="post">
    {% csrf_token %}
    {{ form.as_p }}
<button type="submit">Upload</button>
</form>
like image 29
Omar Elweshy Avatar answered Nov 10 '22 03:11

Omar Elweshy