Django: Getting the page an object is on - python

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.

Related

Django url re_path failed to redirect to the correct view

Django re_path did not match and I don't know the reason why.
urls.py
urlpatterns = [
..
re_path(r'^localDeliveryPayment\?paymentId\=(?P<UUID>[0-9-a-z]{32})$', verifyMobilePayReceived.as_view()),
re_path(r'^localDeliveryPayment$', Payment.as_view(), name = 'localDeliveryPayment'),
..
]
If url
www.example.com/localDeliveryPayment the user is directed to Payment view.
If url www.example.com/localDeliveryPayment?paymentId=00340000610febab0891e9008816d3e9 the user should be directed to verifyMobilePayReceived view. The problem is that right now www.example.com/localDeliveryPayment?paymentId=00340000610febab0891e9008816d3e9 is still directed to Payment view.
You are trying to capture a GET parameter in your URL routing which is the incorrect way of doing what you are trying to do.
Either continue with your current method of passing a paymentId GET parameter and check for its presence in you Payment.as_view() view OR you can rework this to something along the lines of.
re_path(r'^localDeliveryPayment/<UUID:NAME_OF_UUID_IN_MODEL>/', verifyMobilePayReceived.as_view()),
This should provide the filtering for the model you desire.

Passing variables in django browser string

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

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.

Django url routing - include url part for dispatching

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.

Shared/Global Dictionary in Django Between URLs and Context Processor

At runtime I'm trying to generate a tree of parent-child relationships between views using the urls.py of different apps. I'm trying to accomplish breadcrumbs by allowing this tree to be defined by an extension of the url function that accepts extra arguments for view_name (name to display on page when used on page, like "Home") and parent_view (specifies the immediate parent so you can generate your breadcrumb).
This class is defined in a separate file in its own module utils.breadcrumbs. The class is called BreadCrumbs and I try to define an instance of BreadCrumbs in the same file for import into various files. This is where it breaks I think.
utils/breadcrumbs.py
class BreadCrumbs:
breadcrumbs = {} # This is our tree
def url(self, pattern, view, arguments={}, name=None, view_name=None, parent_view=None):
... Adds node to self.breadcrumbs ...
return url(pattern, view, arguments, name)
bc = BreadCrumbs()
app/urls.py
from utils.breadcrumbs import bc
urlpatterns = patterns('',
bc.url(r'^home/$', 'app.views.home', name='home', view_name='Home'),
bc.url(r'^subpage/$', 'app.views.subpage', view_name='Sub Page', parent_view="app.views.home"),
)
Then I try to access the tree defined in breadcrumbs.bc in a context processor using the view name given through a middleware. When I had all of my url patterns in the core urls.py file instead of in separate apps, it worked fine. Now that I've moved the url patterns to separate files, the tree is empty when I go to call it in my context processor using a from utils.breadcrumbs import bc. Am I using global variables incorrectly here? Is there a more correct method to share a variable between my urls.py and my context processor? I've looked at sessions, but I don't have access to the request in urls.py, correct?
Your help is appreciated in advance.

Categories