Javi
Javi

Reputation: 188

Get url variable and value into urlpatterns in Django

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?

Upvotes: 0

Views: 579

Answers (1)

Daniel
Daniel

Reputation: 3527

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

Upvotes: 1

Related Questions