Вопрос

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})
Это было полезно?

Решение

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.

Другие советы

Add enctype="multipart/form-data"

<form enctype="multipart/form-data" method="post">
    {% csrf_token %}
    {{ form.as_p }}
<button type="submit">Upload</button>
</form>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top