Passing variables in django browser string - python

I am doing a search on the page with the ability to filter. It is necessary to pass the selected fields to form the correct queryset. What is the best way to do this? I am creating str variable in urls. But what if you need to pass 10 or more filter conditions? how to organize dynamically passed variables?
urls
from django.urls import path
from .views import *
urlpatterns = [
path('', OrdersHomeView.as_view(), name='orders_home'),
path('filter/<str:tag>', OrdersFilterView.as_view(), name='orders_filter'),
]
I understand what to do through ?var=&var2=, as in php, but I can't figure out how? it is possible to just process the string str, but maybe there is some django magic?

Make the filter view to work with URL GET params:
page = request.GET.get('page', 0)
page_size = request.GET.get('page_size', 100)
Then construct your URLs to send the filters filter/tag/?page=1&page_size=20

Related

Django: Getting the page an object is on

Let's say I have a class Foo. I want to know what page a particular instance of Foo will be on: eg: api.myapp.com/foos/?page=25.
Given an object:
Foo.objects.get(id=500), how can I determine what page my instance will be on?
My approach is a little bit different so you can do this,
model_ids = (list(Model.objects.values_list('id', flat=True)))
This will give you the list of the ids. After that,
get_page_number = model_ids.index(obj_id) // per_page_objects + 1
If the obj_id is 500 so the index will be 499
now if per_page_objects are 10 then it will give you page number by calculating (499 // 10 +1 = 50).
This means your object having an id 500 is on the 50th page.
I hope this will work for you.
Django by itself does not predefine which url your model will be accessed through.
The documentation says - "Django lets you design URLs however you want, with no framework limitations".
So the process is rather opposite:
you define the url (look inside urls.py) and associate it with the view to be called for processing:
from django.urls import path
from . import views
urlpatterns = [
path('foos/', views.foo_list),
path('foos/<int:id>/', views.foo_detail),
you should define the views (usually in views.py)
and inside the view you can call any models to fetch data from DB
You can implement your API with additional packages like Django Rest Framework.
It has Routers that allow you to define a set of urls at once. The following will generate URL patterns like '^foos/$' and '^foos/{pk}/$':
you register your url within the router
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'foos', FooViewSet)
you should implement FooViewSet and make sure your model is used there.

Django: need Dynamic login redirect using info from database redirect after login, using built-in login

After I login, I need to redirect to another page while adding URL parameters to the URL of the next page. I get the value of these parameters after the user is authenticated because they need to be accessed from the user database table. I heard about using the next parameter but I don't know how I would use it since I need to access the database table and I can't do that from urls.py. This is my url.py line for login right now:
url(r'^$',auth_views.login, name='login',kwargs={
'authentication_form':loginPlaceHolderForm,
}),
I'm not really sure what other info you need so just ask for it in the comments and I'll be sure to add it.
Also I'm using Django 1.11
EDIT:
For more clarification: What I want is something like this /colors?team=blue
And let's say the team can be red, blue or green and you get this value from the team column in the given row that you get when the user logs in.
You could try to override djangos class-based view LoginView.
In views.py
from django.contrib.auth.views import LoginView
class MyLoginView(LoginView):
authentication_form = loginPlaceHolderForm
def get_redirect_url(self):
print(self.request.user)
# get data for user here
user_data_query_string = ''
url = '{}?{}'.format(
reverse('app:some-name')
user_data_query_string)
return url
In urls.py
url(r'^$', MyLoginView.as_view(), name='login'),
See also this question about adding GET querystring parameters to djangos HttpRedirect.

How to read parameters from request in django

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

How to use one app to satisfy multiple URLs in Django

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.

Django: How do I create a generic url routing to views?

I have a pretty standard django app, and am wondering how to set the url routing so that I don't have to explicitly map each url to a view.
For example, let's say that I have the following views: Project, Links, Profile, Contact. I'd rather not have my urlpatterns look like this:
(r'^Project/$', 'mysite.app.views.project'),
(r'^Links/$', 'mysite.app.views.links'),
(r'^Profile/$', 'mysite.app.views.profile'),
(r'^Contact/$', 'mysite.app.views.contact'),
And so on. In Pylons, it would be as simple as:
map.connect(':controller/:action/:id')
And it would automatically grab the right controller and function. Is there something similar in Django?
mods = ('Project','Links','Profile','Contact')
urlpatterns = patterns('',
*(('^%s/$'%n, 'mysite.app.views.%s'%n.lower()) for n in mods)
)
Unless you have a really huge number of views, writing them down explicitly is not too bad, from a style perspective.
You can shorten your example, though, by using the prefix argument of the patterns function:
urlpatterns = patterns('mysite.app.views',
(r'^Project/$', 'project'),
(r'^Links/$', 'links'),
(r'^Profile/$', 'profile'),
(r'^Contact/$', 'contact'),
)
You might be able to use a special view function along these lines:
def router(request, function, module):
m =__import__(module, globals(), locals(), [function.lower()])
try:
return m.__dict__[function.lower()](request)
except KeyError:
raise Http404()
and then a urlconf like this:
(r'^(?P<function>.+)/$', router, {"module": 'mysite.app.views'}),
This code is untested but the general idea should work, even though you should remember:
Explicit is better than implicit.

Categories