我正在学习Django,使用基于函数的视图,我正在努力解决以下问题:我在www.example.com中有此路径urls.py
path('user/<str:username>',views.UserProjectList,name='user-projects')
这是应该显示特定用户(客户端)的所有项目。为了达到它,用户名应该是基于函数的视图的参数,但我挣扎如何写这样的视图...我有这个:
def UserProjectList(request,username):
user = User.objects.get(username=username) #THIS IS WRONG and should return id of the user
#user = User.objects.filter(username=username) #also wrong
tag_list = ProjectTagsSQL.objects.all() #ProjectTagsSQL and ProjectSQL are connected
project_list = ProjectSQL.objects.filter(client=user) #ProjectSQL table has column client_id (pk is id in User) and table contains all the projects
context = {
'tagy' : tag_list,
'projecty' : project_list
}
return render(request, 'home_page/user_projects.html', context) #SHOULD THE PARAMETER BE INCLUDED HERE?
我试图用我在互联网上找到的基于类的视图中的代码来激发灵感(这对我很有效,但我没有像在FBV中那样将其与ProjectTagsSQL连接起来,但这是一个不同的问题),但我没有做到
class UserProjectListView(ListView):
model = ProjectSQL
template_name = 'home_page/user_projects.html'
context_object_name = 'data'
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return ProjectSQL.objects.filter(client=user)
有人能帮助我如何处理这种基于函数的视图吗?因为这个解决方案不工作(将返回任何用户)
下面也是ProjectSQL模型(和ProjectTagsSQL模型):
class ProjectSQL(models.Model):
id = models.AutoField(primary_key=True)
country = models.TextField()
city = models.TextField()
time_added = models.DateTimeField(default=timezone.now)
start_date = models.DateField()
end_date = models.DateField()
client = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
managed = False #https://docs.djangoproject.com/en/4.0/ref/models/options/
db_table = 'project'
class ProjectTagsSQL(models.Model):
id = models.IntegerField(primary_key=True)
project = models.ForeignKey(ProjectSQL, on_delete=models.CASCADE)
tag = models.ForeignKey(ProjectTagSQL, on_delete=models.CASCADE)
class Meta:
managed = False # https://docs.djangoproject.com/en/4.0/ref/models/options/
db_table = 'project_tags'
1条答案
按热度按时间clj7thdc1#
您需要编写
user.id
,以便:此外,尝试检查模板变量的名称,无论您是否使用相同的。
**注意:**始终在每条路由的末尾附加
/
,因此应为path('user/<str:username>/'...
。**注意:**基于函数的视图通常用
snake_case
编写,因此最好将其命名为user_project_list
,而不是UserProjectList
。