Home > Back-end >  Get url variable and value into urlpatterns in Django
Get url variable and value into urlpatterns in Django

Time:09-23

I was trying to get the variable and value of a url in urlpatterns in Django. I mean, I want to put in the address of the browser type: https://place.com/url=https://www.google.es/... to be able to make a translator. And be able to pick up the variable and value in the function that receives. At the moment I'm trying to get it with re_path like this:

from django.urls import path, re_path
from . import views

urlpatterns = [
    path('', views.index),
    re_path('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.& ]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F])) ', views.index_traductor),
]

The regex match picks it up, but I don't know how to send it as a value in a variable to receive here:

from django.http import HttpResponse

def index(request):
    
    return HttpResponse("flag")

    
def index_traductor(request, url=''):
    
    return HttpResponse("%s" % url)

I get a blank page. Any ideas?

CodePudding user response:

Uh, no need for regex - why not just use get parameters?

URL: https://place.com/?param1=val1

views.py

def my_view_function(reuqest):

    # unpack get parameters:
    val1 = request.GET.get('param1')

    # do something ...
  • Related