Django Add Test View

Test View

When testing different aspects of Django, it can be a good idea to have somewhere to test code without destroying the main project.

This is optional off course, but if you like to follow all steps in this tutorial, you should add a test view that is exactly like the one we create below.

Then you can follow the examples and try them out on your own computer.


Add View

Start by adding a view called "testing" in the views.py file:

my_tennis_club/members/views.py:

from django.http import HttpResponse

from django.template import loader

from .models import Member

 

def members(request):

  mymembers = Member.objects.all().values()

  template = loader.get_template('all_members.html')

  context = {

    'mymembers': mymembers,

  }

  return HttpResponse(template.render(context, request))

 

def details(request, id):

  mymember = Member.objects.get(id=id)

  template = loader.get_template('details.html')

  context = {

    'mymember': mymember,

  }

  return HttpResponse(template.render(context, request))

 

def main(request):

  template = loader.get_template('main.html')

  return HttpResponse(template.render())

 

def testing(request):

  template = loader.get_template('template.html')

  context = {

    'fruits': ['Apple', 'Banana', 'Cherry'],  

  }

  return HttpResponse(template.render(context, request)) 


URLs

We have to make sure that incoming urls to /testing/ will be redirected to the testing view.

This is done in the urls.py file in the members folder:

my_tennis_club/members/urls.py:

from django. Add Test View


Login
ADS CODE