我已经开发了一种自定义表单,用于使用Bootstrap 4的custom-file-input
类上载文件。
文件的路径显示不正确。
我不知道问题出在哪里。我怎么了?
forms.py
class FileUploadForm(forms.ModelForm):
name = forms.CharField(
max_length=50,
help_text="<small>Write file name here. The name must be have max 50 characters</small>",
widget=forms.TextInput(
attrs={
"placeholder": "Titolo",
"type": "text",
"id": "id_title",
"class": "form-control form-control-lg",
}
),
)
description = forms.CharField(
max_length=200,
help_text="<small>Write a short description here. The description must be have max 200 characters.</small>",
widget=forms.Textarea(
attrs={
"placeholder": "Descrizione",
"type": "text",
"id": "id_description",
"class": "form-control",
"rows": "2",
}
),
)
publishing_date = forms.DateTimeField(
input_formats=['%d/%m/%Y %H:%M'],
label="Data di pubblicazione",
help_text="<small>Write data and hour of publication. You can use also a past or a future date.</small>",
widget=forms.DateTimeInput(
attrs={
"id": "publishing_date_field",
'class': 'form-control datetimepicker-input',
'data-target': '#publishing_date_field',
}
),
)
file = forms.FileField(
help_text="<small>Upload the file here.</small>",
widget=forms.ClearableFileInput(
attrs={
"placeholder": "Carica il file",
"type": "file",
"id": "id_file",
"class": "custom-file-input",
}
),
)
class Meta:
model = FileUpload
fields = [
'name',
'description',
'publishing_date',
'file',
]
views.py
def createFile(request):
if request.method == 'POST':
form = FileUploadForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
return redirect('file_list')
else:
form = FileUploadForm()
context = {
'form': form,
}
template = 'fileupload/editing/upload_file.html'
return render(request, template, context)
def updateFile(request, pk=None):
update_file = get_object_or_404(FileUpload, pk=pk)
form = FileUploadForm(request.POST or None, request.FILES or None, instance=update_file)
if form.is_valid():
update_file = form.save()
update_file.save()
return redirect('file_list')
context = {
'form': form,
}
template = 'fileupload/editing/upload_file.html'
return render(request, template, context)
upload_file.html
<div class="form-group mb-4">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01" value="{{ form.file }}">
<label class="custom-file-label" for="inputGroupFile01">Choose a file</label>
</div>
<label for="id_image">
<span class="text-info" data-toggle="tooltip" title="{{ form.file.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.file.errors }}</small>
</label>
</div>
</div>