Django为用户上传文件

时间:2013-06-25 09:56:19

标签: django

我可以上传django中的文件。我还设法注册了不同的用户。 但是当用户登录时,他们都会看到任何人上传的文件集。 相反,我希望用户只查看他/她上传的那些文件集。

这是我的models.py

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

views.py

def list(request):

    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponse("File Uploaded.. Kindly Refresh!!")
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'login/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )

LIST.html

 <table cellpadding=20>
    {% for document in documents %}
        <tr>
            <td><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a> </td>
            <td></td>
            <td></td>
            <td><a href="delete/{{ document.docfile.name }}"> Delete</a></td>

        </tr>
    {% endfor %}
    </table>

  {% else %}
    <p>No documents.</p>
  {% endif %}

1 个答案:

答案 0 :(得分:2)

将models.py更改为此

from django.contrib.auth.models import User
class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')
    user = models.ForeignKey(User)

将views.py更改为此

def list(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.user = request.user
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponse("File Uploaded.. Kindly Refresh!!")
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.filter(user=request.user)

    # Render list page with the documents and the form
    return render_to_response(
        'login/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )