如何只显示他们上传的用户文件(不是全部)我使用的是python 2.7和django 1.7和django allauth。以下是我的模特。如果有人能指出我正确的方向,谢谢你。
models.py
def hashed_uploads_dirs(instance, filename):
return os.path.join(instance.md5, filename)
class File(models.Model):
f = models.FileField(upload_to='.')
md5 = models.CharField(max_length=32)
created_at = models.DateTimeField(auto_now_add=True)
def was_published_recently(self):
return self.created_at >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'created_at'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
def __unicode__(self):
return self.f.name
@models.permalink
def get_absolute_url(self):
return ('file-add', )
def save(self, *args, **kwargs):
self.slug = self.file.name
super(File, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""delete -- Remove to leave file."""
self.file.delete(False)
super(File, self).delete(*args, **kwargs)
答案 0 :(得分:2)
您需要修改文件类以将外键存储到用户。它应该看起来像
...
from django.contrib.auth.models import User
class File(models.Model):
f = models.FileField(upload_to='.')
md5 = models.CharField(max_length=32)
created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, related_name='uploaded_files')
...
上传文件时,您还必须在保存文件之前设置用户。然后,当您拥有User实例时,您可以使用user.uploaded_files获取所有上传的文件。
答案 1 :(得分:1)
在文件中创建一个新字段:user = models.ForeignKey(User)
然后你可以做
file.user = request.user
file.save()
在处理文件上传的函数
中