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

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'),
]

Related

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

(Django) Trying to figure out how I can get the right product using query parameters on Postman (url.py and views.py)

I have been building a sandwich shop app and I succeesfully build models.py and inserted all the product data. However, when I try to call specific products using Postman and the Django server, it keeps showing 404. What I typed on postman is like so:
http://10.58.1.157:8000/product/sandwich?product_id=1
Below are my codes for urls.py and views.py
So far, I have tried:
urls.py
from django.urls import path
from .views import ProductView
urlpatterns = [
path('sandwich/int:<product_id>/', ProductView.as_view()),
]
and:
urls.py
path('sandwich/(?P<product_id>[\w.-]+)/', ProductView.as_view())
views.py
import json
import bcrypt
import jwt
from django.views import View
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.db.models import Q
from .models import Product, Category, SubCategory
class ProductView(View):
def get(self, request):
product_id = request.GET.get('product_id', None)
return JsonResponse({'product_name':Product.objects.get(id=product_id).values()})
To clarify the GET request, I will add the screenshot of Postman below:
It seems like this is due to malformed URL path. That's whats typically indicative of 404-NotFound error.
You need to add question mark that essentially forms the querystring. It is processed and available as a dictionary-like object (a QueryDict) in request.GET in views.py
You can define it like so, with a ? using a REGEX pattern (You may also alter to your needs)
path('sandwich/(?P<product_id>[\w.-]+)/', ProductView.as_view()),
In your views.py you can filter them with
product_id = request.GET.get('product_id', None)
This should now hopefully return a response now that the URL cannot give a 404 error.
See this for an example
I finally solved the issue!
I looked at this page and improvised accordingly...
https://docs.djangoproject.com/en/3.0/topics/http/urls/#nested-arguments
the final version of request is:
http://127.0.0.1:8000/product/?product_id=1
and the urls.py is:
from django.urls import path, re_path
from .views import ProductView
urlpatterns = [
re_path(r'^(?:\?product_id=(?P<product_id>\d+)/)?$', ProductView.as_view()),
]

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 to check name of Django url in view

say this is my url:
url(r'^$', mainApp_views.homepage),
Is it possible to check this text = "mainApp_views.homepage" in view and middleware ?
Thanks in advance,
You want something like
from django.urls import resolve
def your_view(request):
# resolve the url from the path
url_name = resolve(request.path).url_name
You will probably want to add names to your urls too name='home'
As of Django 2.0, you need to import resolve from django.urls:
from django.urls import resolve
def your_view(request):
url_name = resolve(request.path).url_name
print(url_name) #prints the "name" attribute in your urlpatterns

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