我有这个功能视图。
如何在基于类的视图中转换此函数?
在这种情况下,我使用TemplateView?
def linechart(request):
ds = DataPool(
series=[{'options': {
'source': MonthlyWeatherByCity.objects.all()},
'terms': [
'month',
'houston_temp',
'boston_temp']}
])
cht = Chart(
datasource=ds,
series_options=[{'options': {
'type': 'bar',
'stacking': False},
'terms': {
'month': [
'boston_temp',
'houston_temp']
}}],
chart_options={'title': {
'text': 'Weather Data of Boston and Houston'},
'xAxis': {
'title': {
'text': 'Month number'}}})
return render_to_response('core/linechart.html', {'weatherchart': cht})
返回错误
答案 0 :(得分:3)
class MyTemplateView(TemplateView):
template_name = 'core/linechart.html'
def get_ds(self):
return DataPool(...)
def get_water_chart(self):
return Chart(datasource=self.get_ds() ...)
def get_context_data(self, **kwargs):
context = super(MyTemplateView, self).get_context_data(**kwargs)
context['weatherchart'] = self.get_water_chart()
return context
网址中的应该是这样的
url(r'^$', MyTemplateView.as_view(), name='index'),
答案 1 :(得分:0)
我认为你最好的选择是使用通用的View而不是模板,因为它很容易进行切换。类似的东西:
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.views.generic import View
class LinechartView(View):
def get(self, request, *args, **kwargs):
ds = DataPool(
series=[{'options':
{'source': MonthlyWeatherByCity.objects.all()},
'terms': [
'month',
'houston_temp',
'boston_temp']}
])
cht = Chart(
datasource=ds,
series_options=[
{'options': {
'type': 'bar',
'stacking': False
},
'terms': {
'month': [
'boston_temp',
'houston_temp']
}}],
chart_options={
'title': {
'text': 'Weather Data of Boston and Houston'},
'xAxis': {
'title': {
'text': 'Month number'
}}})
return render(request, {'weatherchart': cht})
# Doing it like this also allows flexibility to add things like a post easily as well
# Here's an example of how'd you go about that
def post(self, request, *args, **kwargs):
# Handles updates of your model object
other_weather = get_object_or_404(YourModel, slug=kwargs['slug'])
form = YourForm(request.POST)
if form.is_valid():
form.save()
return redirect("some_template:detail", other_weather.slug)
我继续进行格式化,尽我所能,试图在stackoverflow中查看它。为什么不使用像pycharm这样的IDE来简化生活(至少在格式化方面)?