1

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

这是我的models.py

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

视图.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)
    )

列表.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 %}
4

1 回答 1

4

将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)
    )
于 2013-06-25T14:38:17.060 回答