D
D
DmSS19972021-12-26 18:11:43
Django
DmSS1997, 2021-12-26 18:11:43

How can I optimize page loading speed on a website?

I have a section with offices on my site, which, in addition to information about objects, also has filtering.
Code from models.py: (The code is not complete, but it doesn't matter, there are around 10 attributes)

class Offices2(models.Model):
    city = models.CharField(max_length=255, choices=Choice_city, blank=True, verbose_name='Город')
    address = models.CharField(max_length=255, blank=True, verbose_name='Адрес')

I needed to add a map to the page with offices, on which the objects will be located, for which I used Folium and GeoCoder. Before adding the map, the page loaded very quickly, even considering that there was filtering and considering the huge number of objects in the database.

Here is the code in views.py before adding the map:
class OfficesPage(ListView):
    model = Offices2
    template_name = 'CatalogTenants/offices.html'
    context_object_name = 'offices'
    paginate_by = 10
    allow_empty = True

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['FilterOffice'] = OfficesFilter(self.request.GET, queryset=Offices2.objects.all())
        context['form'] = ClientsForm()

   def post(self, request):
        if request.method == 'POST':
            form = ClientsForm(request.POST)
            if form.is_valid():
                form.save()
                send_mail(subject=form.cleaned_data['FIO'],
                          message=form.cleaned_data['phone'],
                          from_email='[email protected]',
                          recipient_list=['[email protected]']
                          )
                messages.success(request, 'Заявка отправлена')
                return redirect('offices')
            else:
                messages.error(request, 'Форма заполнена неверно')
                form = ClientsForm()
                return redirect('offices')

    def get_queryset(self):
        queryset = super().get_queryset()
        return OfficesFilter(self.request.GET, queryset=queryset).qs


Here is the code from views.py after adding the map.
class OfficesPage(ListView):
    model = Offices2
    template_name = 'CatalogTenants/offices.html'
    context_object_name = 'offices'
    paginate_by = 10
    allow_empty = True

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['FilterOffice'] = OfficesFilter(self.request.GET, queryset=Offices2.objects.all())
        context['form'] = ClientsForm()
        # Создание карты и изначального её расположения карты #
        m = folium.Map(location=[55.7887400, 49.1221400], zoom_start=7)
        # Получение коордиант из поля "адресс" у модели #
        for office in OfficesFilter(self.request.GET, queryset=Offices2.objects.values('address')).qs:
            location = geocoder.osm(office.get('address'))
            lat = location.lat
            lng = location.lng
            country = location.country
            ##Добавление объекта на карту##
            folium.Marker(location=[lat, lng], tooltip='Нажмите чтобы узнать больше', popup=country).add_to(m)
        m = m._repr_html_()
        context['m'] = m
        return context


And then the problem arises that the more objects in the database, the longer the page loads and I don’t understand what this is connected with, and most importantly, I don’t understand how this can be fixed. I tried to create labels without accessing the database, but simply by placing markers in the view, and then the page loading speed did not change (it was initial, that is, minimal), that is, from here I conclude that the loading time increases due to accessing the database.

The original code was this:
# Создание карты и изначального её расположения карты #
        m = folium.Map(location=[55.7887400, 49.1221400], zoom_start=7)
        # Получение коордиант из поля "адресс" у модели #
        for office in OfficesFilter(self.request.GET, queryset=Offices2.objects.all().qs:
            location = geocoder.osm(office.get('address'))
            lat = location.lat
            lng = location.lng
            country = location.country
            ##Добавление объекта на карту##
            folium.Marker(location=[lat, lng], tooltip='Нажмите чтобы узнать больше', popup=country).add_to(m)
        m = m._repr_html_()
        context['m'] = m
        return context

I thought that I was getting too much unnecessary information and decided to only receive information about addresses, and rewrote the code. You can see it at the beginning. But this did not affect the download speed.
61c8856b652eb512365423.png
61c88581de0d5209416053.png
61c885bc5bde0713996672.png

What is the reason and how to fix it, please help

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question