在我的Django网站上,我有两个模型 - 一个是Project,用户可以创建,一个是Access,用户可以在其中添加其他用户以访问项目。 Access模型包含存储其他用户的manytomanyfield。我可以添加用户并从该字段中删除用户,它在整个站点范围内工作(即如果我将用户添加到项目中,然后登录该用户的帐户,我可以看到它)但是如果我添加多个用户合作者,我将开始在项目流中看到该项目的多次迭代。在我看来,Django向我展示了access_list中每个用户的项目,而不是一次。
Models.py:
class Project(models.Model):
project_name = models.CharField(max_length=200)
project_description = models.TextField(null=True, blank=True)
project_thumbnail = models.FileField(upload_to=get_upload_file_name, null=True, blank=True)
project_pubdate = models.DateTimeField(default=timezone.now)
created_by = models.ForeignKey(User)
def __unicode__(self):
return self.project_name
def save(self):
if not self.id and not self.project_description:
return
super(Project, self).save()
Access.objects.get_or_create(project=self)
if self.project_thumbnail:
size = 200, 200
image = Image.open(self.project_thumbnail)
image.thumbnail(size, Image.ANTIALIAS)
fh = storage.open(self.project_thumbnail.name, "w")
format = 'png' # You need to set the correct image format here
image.save(fh, format)
fh.close()
def get_project_thumbnail(self):
thumb = str(self.project_thumbnail)
if not settings.DEBUG:
thumb = thumb.replace('assets/', '')
return thumb
class Access(models.Model):
project = models.ForeignKey(Project)
access_list = models.ManyToManyField(User)
pubdate = models.DateTimeField(default=timezone.now)
Views.py:
@login_required
def projects(request):
thisuser = request.user
if Access.objects.filter(Q(access_list=thisuser) | Q(project__created_by=thisuser)).exists():
projects_by_username = Access.objects.filter(Q(access_list=thisuser) | Q(project__created_by=thisuser)).order_by('-project__project_pubdate')
else:
projects_by_username = None
return render_to_response('projects.html',
{'projects_by_username': projects_by_username,
'user': thisuser })
projects.html:
{% for project in projects_by_username %}
<table width="100%" cellpadding="5">
<tr>
<td width="25%" rowspan="3"><a href="/projects/get/{{ project.project.id }}">
{% if project.project.project_thumbnail %}
<img src="{% get_static_prefix %}{{project.project.project_thumbnail}}" width="150" /></td>
{% endif %}
</a></td>
<td width="75%" valign="top"><div class="heading16px"><a href="/projects/get/{{ project.project.id }}">{{ project.project.project_name }}</a></div></td>
</tr>
<tr>
<td><a href="/projects/get/{{ project.project.id }}">{{ project.project.project_description }}</a></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
{% endfor %}