Django - TypeError __init__() missing 1 required positional argument when uploading a file
You are doing too much, the file = kwargs.pop('file')
makes no sense: the data is passed as request.FILES
and is passed to the ModelForm
, your ModelForm
can thus look like:
class UploadFileForm(forms.ModelForm):
class Meta:
model = CheckFile
fields = ['file', ]
# no __init__
The same for your view: Django will automatically create the form and pass the data accordingly. If you want to specify the name of the CheckFile
, you can do that in the form_valid
method:
class UploadFileView(CreateView):
form_class = UploadFileForm
template_name = "tool/upload.html"
success_url = reverse_lazy('tool:index')
def form_valid(self, form):
form.instance.name = 'test'
return super().form_valid(form)
If you are submitting files, you should specify enctype="multipart/form-data"
:
<form method="POST" enctype="multipart/form-data">
<p>
{% csrf_token %}
{{ form.as_p }}
</p>
<button type="submit">Save</button>
</form>
and that's all that is necessary.