render two views to a single html template

风格不统一 提交于 2021-02-19 04:54:51

问题


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 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

<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>

single view working corresponding to the URL.


回答1:


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.



来源:https://stackoverflow.com/questions/42132010/render-two-views-to-a-single-html-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!