如何将两个Django视图合并为一个?

enxuqcxy  于 2023-03-31  发布在  Go
关注(0)|答案(1)|浏览(163)

我正在特灵将两个Django视图合并为一个。目标是能够在同一页面上呈现Django表单和folium map。下面是我将视图合并为组合视图的最佳尝试。请让我知道我哪里出错了。

import folium
from django.shortcuts import render
from django.views import View
from django.views.generic import FormView
from .models import StLouisCityLandTax
from .forms import StLouisCityLandTaxForm

class formView(FormView):
    form = StLouisCityLandTaxForm
    template_name = 'maps/partials/_form.html'

    def get(self, request):
        form = StLouisCityLandTaxForm()
        return render(request, 'maps/partials/_form.html', {"form": form})

def folium_map(request):
    properties = StLouisCityLandTax.objects.all()

    # create a Folium map centered on St Louis
    m = folium.Map(location=[38.627003, -90.199402], zoom_start=11)

    # add markers to the map for each station
    for i in properties:
        coordinates = (i.point_y, i.point_x)
        folium.Marker(coordinates).add_to(m)

    context = {'map': m._repr_html_()}
    return render(request, 'maps/partials/_map.html', context)

class CombinedView(View):
    def get(self, request):
        context = {
            'form': form,
            'map': m._repr_html_(),
        }
        return render(request, 'maps/StLouisCityLandTaxSale.html', context)

我尝试了上面列出的代码。

ss2ws0br

ss2ws0br1#

首先,你应该创建一个新的文件,并将其命名为utils.py,然后创建两个函数来完成你的视图的主要工作,如下所示:

utils.py

import folium
from .models import StLouisCityLandTax
from .forms import StLouisCityLandTaxForm

def formViewFunction():
    form = StLouisCityLandTaxForm()
    
    return form

def mapFunction():
    properties = StLouisCityLandTax.objects.all()

    # create a Folium map centered on St Louis
    m = folium.Map(location=[38.627003, -90.199402], zoom_start=11)

    # add markers to the map for each station
    for i in properties:
        coordinates = (i.point_y, i.point_x)
        folium.Marker(coordinates).add_to(m)
        
    return m

utils.py之后,您需要完成视图:

查看次数.py

from django.shortcuts import render
from django.views import View
from .utils import *

def formViewPage(request):
    form = formViewFunction()
    
    context = {
        'form': form,
    }
    
    return render(request, 'template_name.html', context)

def allObjectsMap(request):
    m = mapFunction()
    
    context = {
        'map': m,
    }
    
    return render(request, 'template_name2.html', context)

def both(request):
    form = formViewFunction()
    
    m = mapFunction()
    
    context = {
        'form': form,
        'map': m,
    }
    
    return render(request, 'template_name3.html', context)

相关问题