Instance of django url to views parameter passing

  • 2021-07-22 10:18:30
  • OfStack

1. Adopt? a=1 & b=2 Access

Modify views. py:


views.py
from django.shortcuts import render
from django.http import HttpResponse

def add(request):
  a = request.GET['a']
  b = request.GET['b']
  c = int(a)+int(b)
  return HttpResponse(str(c))

Note: request. GET is similar to a dictionary, and it is better to use request. GET. get ('a', 0). The default a is 0 when a is not passed

Modify urls. py:


url(r'^add/', calc_views.add, name='add'),

Browser access:

http://127.0.0.1:8000/add/?a=4 & b=5

2. Access by/add/3/4/

Modify views. py:

views.py


def add2(request, a, b):
  c = int(a) + int(b)
  return HttpResponse(str(c))

Modify urls. py:


url(r'^add2/(\d+)/(\d+)/$', calc_views.add2, name='add2')

Browser access:

http://127.0.0.1:8000/add/4/5/


Related articles: