我正在尝试通过我的项目上的表单上传一些文件并将文件保存到磁盘。目前,我能够将数据插入数据库(postgreSQL
),但数据没有写入磁盘。我环顾四周,使用 amodelform
和 callsave
应该可以解决所有问题(但显然我错过了一些东西?)。任何帮助表示赞赏。
这是我的代码: views.py(用于上传与工作相关的文件)
# Upload files to a Job (Developer)
@login_required()
@user_passes_test(lambda u: u.groups.filter(name='Developer').exists(), login_url='/login/', redirect_field_name='not allowed')
@require_http_methods(['POST'])
def job_file_upload(request, jobid):
# Get the Job
job = Jobs.objects.get(id=jobid)
fileform = JobFileSubmitForm(request.POST, request.FILES)
if fileform.is_valid():
jfs = fileform.save(commit=False)
file = request.FILES['file']
jfs.user_id = request.user.id
jfs.job_id = jobid
jfs.file = file.name
jfs.uploadDate = datetime.now()
# Save to DB
jfs.save()
return redirect('view_job', jobid=jobid, slug=job.slug)
models.py(用于保存文件数据并保存到正确路径的数据库)
from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location='/media/')
...
def upload_job_file_path(instance, filename):
return os.path.join('/uploads/job_meta/files/', instance.id, filename)
# Submit Files for a Job (Developer Role)
class JobFileSubmit(models.Model):
job = models.ForeignKey(Jobs)
user = models.ForeignKey(User)
file = models.FileField(storage=fs, upload_to=upload_job_file_path, blank=False, null=False)
uploadDate = models.DateTimeField(auto_now=True)
表格.py
class JobFileSubmitForm(forms.ModelForm):
class Meta:
model = JobFileSubmit
fields = 'file',
def save(self, commit=True):
jobfilesubmit = super(JobFileSubmitForm, self).save(commit=False)
if commit:
jobfilesubmit.save()
return jobfilesubmit
视图.html
<form method="post" action="/job/job_file_upload/j{{ job.id }}/" class="form-inline btn-group" enctype="multipart/form-data">
{% csrf_token %}
<div class="span6 inline">
<label class="control-label">Attach Files: </label>{{ job_file_submit.file }}
<p class="help-block">Attach files that go with this Job.</p>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success btn-med pull-left"><i class="fa fa-check-circle"></i> Attach Files</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
TL;DR:目前表单提交,插入数据库,但数据没有写入磁盘和它应该写入的动态路径。例如,数据没有被写入:
/media/uploads/job_meta/files/{{job.id}}/{{file.name}}
感谢您抽时间阅读!任何帮助深表感谢!