call a view several times in another view

55 views
Skip to first unread message

Sebastian Jung

unread,
Jun 18, 2019, 9:29:44 AM6/18/19
to Django users
Hello,

I have a view like this:

def secondmethod(request,entry):

    if request.method='POST':

      return request.POST.get('selection')

   render(request,'eintrag.html','entry':entry)


def test(request):

    if request.method='POST':

      queryresult = model.objects.all()
      for entry in queryresult:
         eintrag = secondmethod(request,entry)

   render(request,'homepage.html')


This is a easy example. I call the view test, in for loop i want to call the view secondmethod several times. In function secondmethod eintrag.html render and the selection return back to test. Then next row from queryresult is submit to secondmethod. Is this possible?





Dan Davis

unread,
Jun 18, 2019, 12:07:18 PM6/18/19
to Django users
I don't think it is a a good idea to call a view from another view, but if you have an underlying function that used to be a view, and you want to call it to do the secondmethod, then that's a good way to begin to do more with Django.   Another good way is to practice using the generic class-based views until they begin to make sense.

One of my developers used to "assume" the request.method was 'POST' in one function, called search_result, and she also had a search_request method which was also a view:

     def search_request(request):
            .... assumes GET ...

     def search_result(request):
            .... assumes POST ...

I created a new function search_view(), and made that the view, the other two are just functions:

     def search_view(request):
         if request.method == 'GET':
              return search_request(request)
         elif request.method == 'POST':
              return search_result(request)
         else:
              return HttpResponseNotAllowed();
Reply all
Reply to author
Forward
0 new messages