将两个视图呈现到单个html模板 [英] render two views to a single html template

查看:51
本文介绍了将两个视图呈现到单个html模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个视图,我想将这些视图呈现到单个HTML页面.我知道如何在HTML页面上呈现单个视图,但不知道如何在单个HTML页面上呈现两个视图.

I have two views and I want to render those views to a single HTML page. I know how to render a single view to an HTML page but don't know how to render two views to a single HTML page.

views.py文件

views.py file

from django.shortcuts import render
from django.http import HttpResponse
from app.models import *
# Create your views here.

def collegeview(request):

    if request.method == 'POST':
        form = collegeform(requst.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('its done here')
        else:
            form = collegeform()
            return render(request, 'about.html', {'form':form})                

def schoolview(request):

    if request.method == 'POST':
        f = schoolform(requst.POST)
        if f.is_valid():
            f.save()
            return HttpResponse('its done here')
        else:
            f = schoolform()
            return render(request, 'about.html', {'f':f})

about.html

about.html

<html>
  <body>
    <h1>its working </h1>
    first view <br>
    <form action ='' method = 'POST'> {% csrf_token %}
        {{form.as_p}}
        <input type='submit' name='submit'>
    </form>

    2nd view<br>
    <form action='' method='POST'>  {% csrf_token %}
        {{f.as_p}}
        <input type='submit' name='submit'>
    </form>
  </body
</html>

与URL对应的单一视图.

single view working corresponding to the URL.

推荐答案

无法将两个不同的视图呈现到同一模板,但是您可以在一个视图中添加这两种逻辑,然后在该视图中呈现这两种形式:来自django.shortcuts的

Not possible to render two different views to the same template, but you can add both the logics in a single view and then render both forms in that:

from django.shortcuts import render
from django.http import HttpResponse
from app.models import *

def institute_view(request):

    f = schoolform(requst.POST or None)
    form = collegeform(requst.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            return HttpResponse('its done here')
        elif f.is_valid():
            f.save()
            return HttpResponse('its done here')
        else:
            f = schoolform()
            form = collegeform()

    return render(request, 'about.html', {'f':f,'form':form})

通过这种方法,可以处理您的两个表单,并且每当任何一个表单发布时,相应的值都将被保存.

By this method, both of your forms can be handled and whenever anyone of them gets posted the values will be saved accordingly.

这篇关于将两个视图呈现到单个html模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆