ProfileFilter
允许用户通过age, location, etc
筛选其他用户。
当它是带有class FilterView(View)
且具有唯一URL的单独页面时,效果很好,但是当尝试将其与主页面结合时,我遇到了问题。
从URL(?interests__icontains=&age=&gender=M
)可以看出,过滤表单正在显示和过滤,但是并未呈现结果。
这显然是因为ProfileFilter
已分配给变量f
,并且页面是使用{% for user in users %}
forloop填充的。
我需要将f
分配给users
,并尝试制作一个单独的def filter
函数,在其中添加context = {'users': f}
,但是该表单没有显示在页面上不再。
我是一个初学者,所以如果我缺少一些关键的东西,请通知我...与往常一样非常感谢,
views.py
class ConnectView(View):
template_name = 'connect/home.html'
def get(self, request, *args, **kwargs):
f = ProfileFilter(request.GET, queryset=Profile.objects.exclude(user=request.user))
context = {
'users': User.objects.exclude(username=request.user),
'filter': f,
}
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
location = Location(latitude=request.POST['latitude'], longitude=request.POST['longitude'], user = request.user)
location.save()
return JsonResponse({'message': 'success'})
def location(request):
if request.POST:
radius_km = request.POST.get('radius', 0)
queryset = User.objects.annotate(
radius_sqr=pow(models.F('loc__latitude') -
request.user.loc.latitude, 2) + pow(models.F('loc__longitude') -
request.user.loc.longitude, 2)
).filter(
radius_sqr__lte=pow(int(radius_km) / 9, 2)
).exclude(username=request.user)
context = {'users': queryset}
return render(request, 'connect/home.html', context)
filters.py
class ProfileFilter(django_filters.FilterSet):
class Meta:
model = Profile
fields = {
'interests': ['icontains'],
'age': ['exact'],
'gender': ['exact'],
}
urls.py
urlpatterns = [
path('', connect_views.ConnectView.as_view(), name='connect_home'),
path('location', connect_views.location, name='location'),
connect_home.html
<!-- filter by age, interest, gender -->
<form method="GET">
{{ filter.form|crispy }}
<button type="submit">Search.</button>
</form>
<!-- enter radius to filter by location-->
<form action="location" method="POST">
{% csrf_token %}
<input type="number" name="radius">
<input type="submit" value=" kilometers">
</form>
{% for user in users %}
<h5><b>{{ user.first_name }} {{ user.last_name }}</b></h5>
{% endfor %}