site.py 1.76 KB
Newer Older
Skia's avatar
Skia committed
1 2
from django.shortcuts import render, redirect, get_object_or_404
from django.db import models
Skia's avatar
Skia committed
3 4 5 6
from django.http import JsonResponse
from django.core import serializers
from django.db.models import Q
from django.contrib.auth.decorators import login_required
Skia's avatar
Skia committed
7

Skia's avatar
Skia committed
8
import os
Skia's avatar
Skia committed
9 10 11 12 13
import json
from itertools import chain

from core.models import User
from club.models import Club
Skia's avatar
Skia committed
14

Skia's avatar
Skia committed
15
def index(request, context=None):
Skia's avatar
Skia committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    return render(request, "core/index.jinja")

def search(query, as_json=False):
    result = {'users': None, 'clubs': None}
    if query:
        nicks = User.objects.filter(nick_name__icontains=query).all()
        users = User.objects.filter(Q(first_name__icontains=query) | Q(last_name__icontains=query)).all()
        clubs = Club.objects.filter(name__icontains=query).all()
        nicks = nicks[:5]
        users = users[:5]
        clubs = clubs[:5]
        if as_json: # Re-loads json to avoid double encoding by JsonResponse, but still benefit from serializers
            nicks = json.loads(serializers.serialize('json', nicks, fields=('nick_name', 'last_name', 'first_name', 'profile_pict')))
            users = json.loads(serializers.serialize('json', users, fields=('nick_name', 'last_name', 'first_name', 'profile_pict')))
            clubs = json.loads(serializers.serialize('json', clubs, fields=('name')))
        else:
            nicks = list(nicks.all())
            users = list(users.all())
            clubs = list(clubs.all())
        result['users'] = nicks + users
        result['clubs'] = clubs
    return result

@login_required
def search_view(request):
    return render(request, "core/search.jinja", context={'result': search(request.GET.get('query', ''))})

@login_required
def search_json(request):
    return JsonResponse(search(request.GET.get('query', ''), True))
Skia's avatar
Skia committed
46