I'm trying to return a list of users with a particular skill and skills is a TagField (django taggit) in a CustomUser model. I'm struggling to get the queryset right in my ListView (skill_list.html). I want to be able to click on the skill listed on a user's profile (profile.html) and then have that return the skill list page with a list of all users that have that skill.
models.py:
class CustomUser(AbstractUser):
objects = CustomUserManager()
position = models.CharField(max_length =200, null=True, default='',
blank=True)
bio = models.CharField(max_length=400, null=True, default='',
blank=True)
skills = TaggableManager(help_text="A comma-separated list of tags.")
views.py:
class SkillView(ListView):
model = CustomUser
template = 'skill_list.html'
queryset = CustomUser.objects.all()
def get_queryset(self):
queryset = CustomUser.objects.filter(skills__name__in=
[self.kwargs['skill']])
return queryset
profile.html:
<div class="container-fluid" id="profile_container">
<div class="container skills">
{% for skill in user.skills.all %}
<div class="skill_bubble"><p class="skill_bubble"><a href="
{% url 'skills' %}">{{ skill.name }}</a></p></div>
{% endfor %}
</div>
</div>
skill_list.html:
<div class="container">
{% for user in object_list %}
<div class="container user_name">
<p class="profile_name"><a href="{% url 'profile_with_pk'
pk=user.pk %}">{{ user.first_name }} {{ user.last_name }}</a></p>
<p class="profile_text">{{user.position}}</p>
</div>
</div>
I have the url set up on the profile page to return the 'skill_list.html', however I get an key error on the skill_list page: Exception value "skill."
答案 0 :(得分:1)
我希望能够点击用户个人资料(profile.html)上列出的技能,然后返回该技能列表页面
在这种情况下,URL需要在其中包含技能,例如/skills/python/
或/skills/sql/
。
您可以通过将URL更改为以下内容来实现:
path('skills/<slug:skill>', views.SkillView.as_view(), name='skills')
现在self.kwargs['skill']
将以SkillView.get_queryset
方法工作。
您现在需要在URL标记中包括该技能,例如:
{% url 'skills' skill %}
最后,由于您只使用列表中的单个项目,
queryset = CustomUser.objects.filter(skills__name__in=[self.kwargs['skill']])
您可以删除__in
并将查询更改为:
queryset = CustomUser.objects.filter(skills__name=self.kwargs['skill'])
答案 1 :(得分:0)
我认为应该是:request.user
,而不是profile.html中的user
答案 2 :(得分:0)
然后,为什么不使用“ Q”搜索查询呢?在文档中检查