Get url variable and value into urlpatterns in Django - python

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?

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

Avoid Django form being resubmitted by using HttpResponseRedirect

My views.py runs code fine when I press a button on my HTML page, views.py:
def start_or_end_fast(request):
#If starting fast, add a row to the db:
#fast_finished = False
#start_date_time using = current time
#end_date_time using = current time
if request.method == 'POST' and 'start_fast' in request.POST:
add_fast = logTimes(fast_finished=False,start_date_time=datetime.now(),end_date_time=datetime.now())
add_fast.save()
print(add_fast.start_date_time,add_fast.end_date_time)
print('Fast started')
#return render(request,'startandstoptimes/index.html')
return HttpResponseRedirect('startandstoptimes/index.html')
You can see my commented return line, this works but when I refresh the page I can resubmit the data, I want to avoid this. In researching my solution, I saw this could be solved using HttpResponseRedirect but I am not able to get this to work with my code, the more I change the more broken things become.
My application urls.py:
from turtle import home
from django.urls import path,include
from . import views
urlpatterns = [
path('', views.start_or_end_fast,name="start_or_end_fast")
]
My project urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('startandstoptimes.urls'))
]
I believe it is related to the URLs, due to the 404 message I see:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/startandstoptimes/index.html
Using the URLconf defined in myfastingsite.urls, Django tried these URL patterns, in this order:
admin/
[name='start_or_end_fast']
The current path, startandstoptimes/index.html, didn’t match any of these.
Am I going down the right route trying to use HttpResponseRedirect or is there a better solution?
class HttpResponseRedirect¶
The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g.
'https://www.yahoo.com/search/'), an absolute path with no domain
(e.g. '/search/'), or even a relative path (e.g. 'search/'). In that
last case, the client browser will reconstruct the full URL itself
according to the current path. See HttpResponse for other optional
constructor arguments. Note that this returns an HTTP status code 302.
See this link for more details: docs
As what the documentation says, HttpResponseRedirect accepts URL and not the path of your template. You should be doing it something like this:
from django.urls import reverse
return HttpResponseRedirect(reverse('start_or_end_fast'))

Django url dispatcher calls the wrong function

the problem that I have is this one:
I created a new re_path in my urls.py file, but when I make a request at that url the wrong function is called.
# myapp/urls.py
from django.urls import path, re_path
from . import views as multiplayer_lite_views
urlpatterns = [
# other paths
re_path(r'vote/(?P<match_id>\w{16})', multiplayer_lite_views.vote, name='multiplayer_lite_vote'),
re_path(r'nightvote/(?P<match_id>\w{16})', multiplayer_lite_views.night_vote, name='multiplayer_lite_night_vote'),
path('new-match/', multiplayer_lite_views.new_match, name='multiplayer_lite_new_match'),
path('', multiplayer_lite_views.home, name='multiplayer_lite_home'),
]
what I did was simply duplicate the line re_path(r'vote/... and renamed it to re_path(r'nightvote/... but changing also all the other info, like multiplayer_lite_views.vote to multiplayer_lite_views.night_vote.
The problem is that when I go to this url nightvote/ the function vote is called.
# myapp/views.py
def vote(request, match_id):
print('vote function')
# do other stuff
return return JsonResponse(...)
def night_vote(request, match_id):
print('nightvote function')
# do other stuff
return return JsonResponse(...)
In the server side what I see is that:
...
vote function
[18/Mar/2020 10:19:16] "POST /nightvote/gfvkpvhlwlqzosae HTTP/1.1" 200 16
...
PS I have already tried to close Django and reopen, the same with vs code.
change your url re_path like as below:
re_path(r'^vote/(?P<match_id>\w{16})$', multiplayer_lite_views.vote, name='multiplayer_lite_vote'),
re_path(r'^nightvote/(?P<match_id>\w{16})$', multiplayer_lite_views.night_vote, name='multiplayer_lite_night_vote'),
I had this problem and this was because ^.

I want to use url's data in method in django

I want to use url's data in method. Now urls.py is
from django.urls import path
from . import views
urlpatterns = [
path('data/<int:id>', views.data, name='data'),
]
I wrote in views.py
#csrf_exempt
def data(request,<int:id>):
results = Users.objects.filter(user=id)
print(results)
return HttpResponse('<h1>OK</h1>')
But I got an error, formal parameter name expected in <int:id> of (request,<int:id>). If I access http://127.0.0.1:8000/data/3, my ideal system print user's data has id=3. I cannot understand how I can do it. What is wrong in my code?
You can't do <int:id> in the parameters for data, that's invalid syntax. It should be just a normal parameter:
def data(request, id):
You have to provide only id in the parameter for data as #Daniel Roseman said
Like this:
def data(request, id):
and in the urls:
from django.urls import path
from . import views
urlpatterns = [
path('data/<id>', views.data, name='data'),
]

how to create a url pattern on path(django 2.0) for a *item*_id in django

Here's my code
from django.urls import path
urlpatterns = [
# /audios/
path('', views.audio ),
# /audios/4344/
path('(<record_id>[0-9]+)/', views.record_detail),
]
Please can someone help out
try this :
path(r'^record/(?P<record_id>[0-9]+)/$', views.record_detail)
Django 2.0 has came with new update of defining a new way for url patterns by path. In new url patterns you don't need to define urls in regex(see 3rd url pattern). Refer
But you can also write url patterns like we define in django < 2. 0 by re_path which is available in django.urls refer
Or you can use old django style of defining url patterns which is defined in django.conf.urls which helps you to define re pattern for urls.
from django.urls import re_path, path
from djnago.conf.urls import url,include
urlpatterns += [
url('(<record_id>[0-9]+)/',views.record_detail),
#or
re_path('(<record_id>[0-9]+)/', views.record_detail),
#or
path('<int:record_id>/', views.record_detail)
]
Just like #Exprator wrote, the path should be:
path('<int:record_id>/', views.record_detail, name='record_detail'),
However, I think maybe there is a problem in view "record_detail", the view should declare like this:
def record_detail(request, record_id):
then, you can refer your record_id in your view body.
Here is my code:
urlpatterns = [
path('', views.index, name='index'),
path('<int:record_id>/', views.record_detail, name='record_detail'),
]
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world.")
def record_detail(request, record_id):
return HttpResponse("Hello, world. You're record is: "+str(record_id))
Here is result:

How can I handle query "?" in my django urls.py

I am new to Django. I have to write a moke. My server will look at a specific address.
Like this:
portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999
I wrote:
urls.py
from django.conf.urls import patterns, url
from rt_moke import views
urlpatterns = patterns('',
url(r'code=(?P<code_id>\w+)/', views.Sapata, name='sapata'),
)
and views.py
from django.http import HttpResponse
status = {u"99999": u'{"code": "99999","status": "undelivered"}',\
u"88888": u'{"code": "88888","status": "delivered"}',\
}
def Sapata(request, code_id):
return HttpResponse(status[code_id])
When I request for portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999 without ? mark - it works, and with ?- not. I understand, that it is query string and Django skips it in the regexp. So what can I do?
This URL:
portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999
has two parts, the path:
portal/client_api.ashx
and the query string:
client=SAPRA&key=1234234&func=status&code=99999
which is parsed into request.GET.
In views.py you should get params from request (like simple dict in request.GET), for example:
def test(request):
code = request.GET.get('code') # here we try to get 'code' key, if not return None
...
and of course, we can't use GET params to parse URLs in urls.py. Your urls.py should looks like:
from django.conf.urls import patterns, url
from rt_moke import views
urlpatterns = patterns('',
url(r'^portal/client_api\.ashx$', views.Sapata, name='sapata'),
)
P.S. Please, don't use capital letters in names of functions.

Categories