I need to read some parameters being passed in and perform some action in django. How can I do that.
url = 172.15.20.116/request
and server is requesting with below parameters
url = 172.15.20.116/request/1289/
here 1289 is parameter. How to parse it?
To so this you need to capture this in the urls.
You will need to look into the django url dispatcher this page has pretty much everything you need to get started. Take your time, learn and then implement.
Maybe something like:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^request/(?P<id>\d+)/$', 'appname.views.my_request_view'),
]
views.py
def my_request_view(request, id):
... # logic goes here
Related
So the url I am trying to achieve looks like this:
127.0.01:8000/api/tech/?belongs=id
My router looks like this:
router = routers.DefaultRouter()
router.register('tech', TechViewSet, basename="tech")
urlpatterns = [
path('', include(router.urls)),
re_path(r'^tech/(?P<belongs>)$', include(router.urls), name="info"),
My viewset looks like this (Also has a retrieve and list functions):
#action(detail=True, url_path='^tech/(?P<belongs>)$', methods=['get'])
def retrieve1(self, request, group=None):
pass
And the router is obviously included in urls.py of main project
How to get this url working.. 127.0.01:8000/api/tech/?belongs=id
Please help. and Im sorry, I'm still learning and the routing part is confusing..
Thankyou so much
It's a little tricky without knowing your model structure. But if you're using your get parameters for filtering you can use django_filters to do the heavy lifting for you. Something like this:
pip install django-filter
add this to your rest framework settings:
'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend']
Then in your TechViewSet you can add filterset_fields:
class TechViewSet:
<your other variables>
filterset_fields = ['belongs',]
you can then add query parameters ?belongs=<some_id> to your url and your results will be filtered.
docs:
https://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend
I have a index.html page with a list of "cards", where each card have a "Click to Select" link.
When user click in this link i'd like to call a function in python to select this item, see:
def selectItem(request, item):
#so something with this item
so, in my html pagE:
<div class="card-action">
Selecionar
</div>
This don't work. What is the right way to do it ?
You can not call a function like that. A browser requests data with an HTTP request, and the server answers with an (HTTP) response. Such requests have a URL, and Django can route the request - with the URL - to the right view that will calculate a response.
We thus need to construct a view that can then be called. Your call is already quite close:
# app/views.py
from django.http import HttpResponse
def select_item(request, item_id):
# so something with this item_id
# ...
return HttpResponse()
Since most objects are not serializable (and usually you do not want that anyway, since it would expose a lot of (potentially sensitive) data to the user, we thus need to work with an id (an identifier that is for example stored in the database that corresponds to an object).
The response contains the data in the response. Frequently that is HTML code that is then rendered by the browser.
Now in urls.py, we can specify how the url looks like, for example:
# app/urls.py
from django.urls import path
from app.views import select_item
urlpatterns = [
path('select_item/<int:item_id>/', select_item, name='select_item_view'),
# ...
]
The urlpatterns need to be included in the root urlpatterns (in the project root).
Now in the HTML template, we can generate the URL that matches with this view, something similar to:
<div class="card-action">
Selecionar
</div>
Django will then make sure that the href points to an URL that refers to the select_item view with the correct parameter.
While using the Routes library I want to redirect certain URLs. The documentation says it can be achieved like this:
map.redirect("/legacyapp/archives/{url:.*}", "/archives/{url}")
And I am indeed able to redirect to a URL this way. However I am unable to map/parse the URL arguments from the request to the redirect. My code looks like this:
app.mapper.redirect( "/repository/status_for_installed_repository{url:.*}", "/api/repositories/check_updates/{url}" )
and if the app is passed this:
curl -L 'FQDN/repository/status_for_installed_repository?owner=qqqqqq&changeset_revision=e5f6ced3e91f&name=asdsadsadas'
it redirects me to
GET /api/repositories/check_updates
but I cannot find a way how to obtain the values of owner name and changeset_revision.
I expect this to be a common use case as generally you do not want to lose arguments when redirecting?
Any help is much appreciated. Thanks.
I ended up implementing it as follows:
def _map_redirects( app ):
"""
Add redirect to the Routes mapper and forward the received query string.
Subsequently when the redirect is triggered in Routes middleware the request
will not even reach the webapp.
"""
def forward_qs(environ, result):
qs_dict = urlparse.parse_qs(environ['QUERY_STRING'])
for qs in qs_dict:
result[ qs ] = qs_dict[ qs ]
return True
app.mapper.redirect( "/repository/status_for_installed_repository", "/api/repositories/check_updates/", _redirect_code="301 Moved Permanently", conditions=dict( function=forward_qs ) )
return app
can i substitute the 2 url routes
urlpatterns = patterns('',
url(r'service/geticons', 'core.service.geticons'),
url(r'service/getnearby', 'core.service.getnearby'),
by a single, more generic, route that routes all requests to the function in the service module with the name of the last url segment?
thinking about something like
url(r'service/#f', 'core.service.#f')
or must i do such dispatch in the service module in django?
Sure, you could collect the path and point it to a view that returns the function.
url(r'service/(?P<function>\w+)/$', 'core.service.function_router')
def function_router(request, function):
return globals()[function](request)
But, it's probably better just to explicitly set the urls.
I'm trying to use one app to satisfy multiple url paths. That is to say, I want the url /blog/ and /job/ to use the same app, but different views. There are a number of ways to do this I'm sure, but none of them seem very clean. Here's what I'm doing right now
# /urls.py
urlpatterns = patterns("",
(r"^(blog|job)/", include("myproject.myapp.urls")),
)
# /myapp/urls.py
urlpatterns = patterns("myproject.myapp.views",
(r"^(?P<id>\d+)/edit/$", "myproject.myapp.views.edit"),
(r"^(?P<id>\d+)/delete/$", "myproject.myapp.views.delete"),
(r"^(?P<id>\d+)/update/$", "myproject.myapp.views.update"),
(r"^insert/$", "myproject.myapp.views.insert"),
)
urlpatterns += patterns("",
(r"^(?P<object_id>\d+)/$", "django.views.generic.list_detail.object_detail", info_dict, "NOIDEA-detail"),
(r"^/$", "django.views.generic.list_detail.object_list", info_dict, "NOIDEA-community"),
)
# /myapp/views.py
def edit(request, type, id):
if (type == "blog"):
editBlog(request, id)
else (type == "job")
editJob(request, id)
def editBlog(request, id):
# some code
def editJob(request, id):
# some code
I've ended up breaking all of this into multiple model and view files to make the code cleaner but the above example doesn't account for things like reverse url lookups which breaks all of my template {% url %} calls.
Originally, I had blogs, jobs, events, contests, etc all living in their own apps, but all of their functionality is so similar, that it didn't make sense to leave it that way, so I attempted to combine them... and this happened. You see those "NOIDEA-detail" and "NOIDEA-community" url names on my generic views? Yeah, I don't know what to use there :-(
You can have more than one modules defining URLs. You can have /blog/ URLs in myapp/urls.py and /job/ URLs in myapp/job_urls.py. Or you can have two modules within a urls subpackage.
Alternatively you can manually prefix your url definitions:
urlpatterns = patterns("myproject.myapp.views",
(r"^jobs/(?P<id>\d+)/edit/$", "myproject.myapp.views.edit"),
(r"^jobs/(?P<id>\d+)/delete/$", "myproject.myapp.views.delete"),
(r"^jobs/(?P<id>\d+)/update/$", "myproject.myapp.views.update"),
(r"^jobs/insert/$", "myproject.myapp.views.insert"),
)
urlpatterns += patterns("",
(r"^blog/(?P<object_id>\d+)/$", "django.views.generic.list_detail.object_detail", info_dict, "NOIDEA-detail"),
(r"^blog/$", "django.views.generic.list_detail.object_list", info_dict, "NOIDEA-community"),
)
And then mount them as:
urlpatterns = patterns("",
(r"", include("myapp.urls")),
)
Personally I would go for more RESTful URL definitions though. Such as blog/(?P<post_id>\d+)/edit/$.
Looks pretty good to me. If you want reverse lookups, just have a different reverse name for each url format, even if they end up pointing to the same view.