Django:上传文件并保存到磁盘

时间:2013-12-09 04:00:01

标签: python django django-models django-views django-file-upload

我正在尝试通过项目中的表单上传一些文件并将文件保存到磁盘。目前,我能够将数据插入到数据库(postgreSQL)中,但数据没有写入磁盘。我已经做了一些环顾四周,使用modelform和调用save应该照顾一切(但显然我错过了什么?)。任何帮助表示赞赏。

这是我的代码: 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)

forms.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

view.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:目前表单提交,插入到DB中,但数据不会写入磁盘和动态路径。例如,数据未写入:

/media/uploads/job_meta/files/{{job.id}}/{{file.name}}

感谢您花时间阅读本文!非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

我不确定这是否是最终答案,但这里更容易编写代码块

upload_job_file_path需要从MEDIA_ROOT返回相对路径。 如果我理解正确,则id是实例的job_id而不是其id。 这样,以下功能应该起作用。 (可能是FileField必须低于代码中的作业字段)

models.py

def upload_job_file_path(instance, filename):
    return 'uploads/job_meta/files/%s/%s' % (instance.job_id, filename)


class JobFileSubmit(models.Model):
    job = models.ForeignKey(Jobs)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=upload_job_file_path, blank=False, null=False)
    uploadDate = models.DateTimeField(auto_now=True)

我不太熟悉模式,但我认为save方法也应该处理文件上载。 所以这可能就足够了

views.py

if fileform.is_valid():
    jfs = fileform.save(commit=True)