我正在创建一个博客站点,用户可以使用属于用户模型的first_name,last_name搜索其他用户。搜索结果将显示
first_name,last_name,username(来自用户模型) profile_image,city,country from(user_profile model)
以下是我的models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
profile_image = models.ImageField(default='', blank=True, null=True)
def __str__(self):
return "Profile of {}".format(self.user.username)
以下是我的views.py
class ProfileList(ListView):
model = User
template_name = 'accounts/profile_list.html'
def get_queryset(self):
queryset = super(ProfileList, self).get_queryset()
query = self.request.GET.get('q')
if query:
queryset = queryset.filter(
Q(user__username__iexact=query)|
Q(user__first_name__iexact=query)|
Q(user__last_name__iexact=query)
)
return queryset
以下是我的模板
<div class="col-md-8">
# I know this is not correct
{% for user in User.objects.all %}
{{user.first_name}} {{user.last_name}}
{{ user.profile_image.url }}
{{user.username}}
{{ user.profile.city }}
{{ user.profile.country }}
{% endfor %}
</div>
我再次学习Django任何帮助都非常感谢。错误尝试解决此问题后,我一直遇到错误
下面的代码消除了错误,但搜索没有返回任何结果
class ProfileList(ListView):
model = User
template_name = 'accounts/profile_list.html'
def get_queryset(self):
queryset = super(ProfileList, self).get_queryset()
query = self.request.GET.get('r')
if query:
queryset = queryset.filter(
Q(profile__user__username__iexact=query)|
Q(profile__user__first_name__iexact=query)|
Q(profile__user__last_name__iexact=query)
)
return queryset