使用日期和用户django保存文件

时间:2017-05-23 09:15:23

标签: python django forms

我正在制作一个上传页面,我想要一个模型,它将保存上传文件,日期和用户的链接。 我是django的新手,我对表单和模型之间的关系以及如何传递数据感到困惑。

我想创建 1字段表单,这将是FileField并捕获request.user和时间,然后将它们保存在数据库中 到目前为止,这是我的代码:

forms.py

class UploadForm(forms.Form):

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user',None)
        super(UploadForm, self).__init__(*args, **kwargs)

    docfile=forms.FileField(label="Select a file")

views.py

@login_required
def upload(request):

    if request.method == "POST":

        form=UploadForm(request.POST, request.FILES, user=request.user)

        if form.is_valid():
            #this is what i used to save the only the file
            #now i want to have file,user and upload date in db
            new_doc = Document(docfile=request.FILES['docfile'])
            new_doc.save()

            print(request.user)
            **???**-what do i insert here to pass user and time
            to the model and save it **???**


            return HttpResponseRedirect(reverse('after_upload'))

    else:


        form=UploadForm()

    return render(request, 'upload.html', {'form':form})

models.py

class Document(models.Model):


    upload_user=**???**
    upload_time=**???**

    docfile=models.FileField(upload_to='documents/%Y/%m')

1 个答案:

答案 0 :(得分:1)

你可能需要做这样的事情,

<强> models.py

from django.contrib.auth.models import User

class Document(models.Model):
    upload_user = models.ForeignKey(User, related_name='documents')
    upload_time = models.DateTimeField(auto_now_add=True)
    docfile  =models.FileField(upload_to='documents/%Y/%m')

<强> forms.py

class UploadForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user',None)
        super(UploadForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Document
        fields = ('docfile',)

<强> views.py

if form.is_valid():
    doc = form.save(commit=False)
    doc.upload_user = request.user
    doc.save()
    return HttpResponseRedirect(reverse('after_upload'))