单个模板上的两个功能视图

时间:2015-07-29 12:19:37

标签: python django django-templates django-views

我有两个函数视图,我希望它们在单个模板上呈现它们。这两种观点有不同的形式。

def user_query(request):
    form_user = Search_User(request.POST)
    no_user = "User Not Found"
    if form_user.is_valid():
        user_name = str(form_user.cleaned_data['user_name'])  
        query = WatchedVideo.objects.filter(user = user_name)
        data_source = ModelDataSource(query,fields=['videoData_id', 'time'])
        pie_chart = gchart.PieChart(data_source,options={'title': user_name + "Video Data"})
        context = {
                'form_user' : form_user,
                "data_source": data_source,
                "pie_chart": pie_chart,
                }
        return render(request,'chart2.html', context)

def select_chart_form(request):
        form = SelectChart(request.POST)
        if form.is_valid():
        chart_type = str(form.cleaned_data['status_chart_type'])
        if (str(form.cleaned_data['status_chart']) == '1'):
            analysis = VideoData.objects.annotate(watches_count = Count('user')).order_by('-watches_count')[:10]
            data_source = ModelDataSource(analysis,fields=['video_name', 'watches_count'])
            column_chart = gchart.ColumnChart(data_source,options={'title': "Top 10 Videos watched by No. Of Users"})
            pie_chart = gchart.PieChart(data_source,options={'title': "Top 10 Videos watched by No. Of Users"})
            context = {
                'form_record' : form_record,
                'chart_type' : chart_type,
                'form' : form,
                "data_source": data_source,
                "column_chart": column_chart,
                "pie_chart": pie_chart,
            }
            return render(request,'chart2.html', context)

上面是我的两个函数视图,我想在单个url上呈现 我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

嗯,你必须把这两个功能合二为一:

def mixin(request):
    context = {}
    context['user_query'] = user_query(request, mix=True)
    context['select_chart_form'] = select_chart_form(request, mix=True)
    return render(request,'chart2.html', context)

def old_view(request, mix=False):
   "your_code"
   if mix:
       return context
   else:
       return render(request,'chart2.html', context)

通过这种方式,您可以以相同的方式或以混合的方式继续使用旧视图。

答案 1 :(得分:0)

从技术上讲,如果目标只是为两种不同的表单使用相同的模板,则无需使用相同的URL。

设置两个指向每个视图功能的单独网址。

在您的视图中,您可以向上下文添加参数,以便自定义表单元素的外观(例如,提交按钮上的文本)或模板的其他特定行为

<form enctype="multipart/form-data" method='POST' action=''>
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="{{ user_query|yesno:"UserQuery,SelectChart"}}">
</form>

然后在模板中:

user_query

有关如何在模板中显示表单元素的更多详细信息和选项,请参阅here

注意:select_chart_form视图函数中,确保表单与context = { 'form' : form_user, "data_source": data_source, "pie_chart": pie_chart, } 视图函数中的名称一起传递:

ActiveRecord::Base.find_by_sql