django/tastypie urls used within views - django

These are my urls:
v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(CategoryResource())
urlpatterns = patterns('',
url(r'^api/$', views.index, name='index'), # welcome page
url(r'^api/v1/$', views.index, name='index'), # welcome page
(r'^api/', include((v1_api.urls))), # model urls
url(r'^docs/', include('docs.urls')), # docs pages
)
I'm providing a GUI for the API and I'd like buttons to link actual tastypie API commands, e.g. http://localhost:8000/api/v1/user/?format=json. If I have a standard django view, I can just type <a href="{% url 'api.views.users'%}" inside the .html file (api = app name, users = a view). How can I achieve this using tastypie?

Have you looked at Swagger?
Swagger is a specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services.
And to connect it with Tastypie: django-tastypie-swagger

This is not very well documented, but you can see the view names in the source code. So you can do stuff like:
{% url api_dispatch_list resource_name='user' api_name='v1' %}
{% url api_dispatch_detail resource_name='user' api_name='v1' pk=5 %}
Here are more details.

Related

i am facing issue to add path to product urls.py file ,i dont know how

```
I am creating CRUD for categories I make a CategoriesViewSet.
on the other hand, I register the router as default in urls.py(Products) for viewset of categories but I don't know how to add a path into the product => urls.py and also the path I want to include into the core url.py file.
product => urls.py
router =routers.DefaultRouter()
router.register(r'categories', CategoryViewSet)
urlpatterns = [
path('list/',ProductList.as_view(),name="View Product"),
path('add/',AddProduct.as_view(),name="Create Product"),
path('<int:pk>/',ProductDetails.as_view(),name="product_detail"),
# path('categories/', CategoryViewSet.as_view({'get':'list'}))
path(r'^', include(router.urls)),
re_path(r'categories/', CategoryViewSet.as_view({'get':'list'}),
name='product-detail')
]
Core => urls.py
path('admin/', admin.site.urls),
path('api/product/', include('products.urls')),
path('api/user/', include('user.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns = format_suffix_patterns(urlpatterns)
I don't think you have a clear idea of what Routers do in Django.
From DRF's official documentation:
Some Web frameworks such as Rails provide functionality for
automatically determining how the URLs for an application should be
mapped to the logic that deals with handling incoming requests.
REST framework adds support for automatic URL routing to Django, and
provides you with a simple, quick and consistent way of wiring your
view logic to a set of URLs.
This line:
router.register(r'categories', CategoryViewSet)
according to Django REST Framework's (DRF) documentation, generates 2 URL patterns:
categories/ - Return the list of categories
categories/{pk}/ - Return category with specified primary key (pk)
You don't need to add those again in Product's urls.py. You can either only specify the router.register(...) method, or manually add them like that:
path('categories/', CategoryViewSet.as_view(), name='product-detail')
It works. In my view I implemented and it works that's why I am asking First of all we have to add the
import [re_path and include] in the Urls.py (Products)
then we have to add--------------------
~the code will be added in the urls.py(Products) below the import library.
router = routers.SimpleRouter()
router.register(r'', CategoryViewSet, 'categories')
in Url Patterns~
re_path(r'^categories/',include((router.urls,'categories'),namespace='categories'))
it works.

Multiple auth login pages in Django

I have multiple apps in one django project
/user
/manager
/business`
Each needs a separate set of login and registration. How do I use django.contrib.auth to satisfy this?
I have urlpatterns in main are:
urlpatterns = [
path('admin/', admin.site.urls),
path('user/', include('user.urls')),
path('user/', include('django.contrib.auth.urls')),
path('manager/', include('manager.urls')),
path('manager/', include('django.contrib.auth.urls')),
path('business/', include('business.urls')),
path('business/', include('django.contrib.auth.urls')),
Urlpatterns in the apps are like those:
urlpatterns = [
path('index', views.index, name='index'),
path('register', views.register, name='register'),
]
and I have different views for login and register, also have different templates in each app: /templates/register/register.html and /templates/register/login.html
However, login and register views seem to be shared between apps. Is there a way to separate them with ease?
First of all I would suggest you make use namespaces in your urls so you don't get any conflicts with the names in your urls. So add app_name to the urls.py of your apps, e.g.
#user urls.py
app_name='user'
urlpatterns = [
...
Then something like {% url 'user:register' %} will point to register view of your user app, {% url 'manager:register' %} will point to the register view of your manager app and so on.
If you have defined individual login views for each app the same goes for these views too, providing you have imported the correct views in you apps urls.py.
As you are also including the django.contrib.auth.urls in each of your apps there is of course a second 'login/' path coming from the default path in the auth.urls. However, as far as I know the resolution of urls is done top down by django, so if you keep the order of urls as in your post your custom 'login/' will be hit first and used. So no problem with that.
Where I see a problem is with your templates. If I understand it correctly all are located in a templates/register/ folder in your apps. The django template loader does not differentiate between a register.html template in your user app and a register.html template in your manager app. So it is likely that you do not get the correct template. What I would suggest is moving the templates to an app specific subfolder, e.g. /templates/user/register. Then you can fetch the correct templates in your views (e.g. 'user/register.html').
I understand that you have individual app specific views. Of course you can always subclass the views django provides and adapt them to your needs. For instance by overriding the form_valid() method of the LoginView. This SO post provides an example.
If on the other hand you want to use the default django login view just with a custom template you can pass the template as a kwarg to your view. E.g.:
# user urls.py
from django.urls import path
from django.contrib.auth.views import LoginView
app_name='user'
urlpatterns = [
path('login/', LoginView.as_view(template_name='user/login.html'), name='login'),
# more patterns
]
If you want to redirect to some custom site after successful login you can add an input called 'next' to your login form containing the url to where to redirect, e.g.
<!-- user/login.html -->
<form action="{% url 'user:login' %}" method="POST">
{% csrf_token %}
{{ form }}
<input type="hidden" name="next" value="/user/index/">
<button type="submit">Login</button>
</form>
In your apps you will propably be using the user_passes_test decorator or something similar to check whether the user is allowed to access the view in that app.

How do create url to django Admin within my user page (HTML)

I'm new to coding, I'm trying to create URL link in NavBar to redirect my Django Admin exmple:
<a class="nav-link" href="{% url 'admin'%}"> Admin site </a>
However, Django do find; No-Reverse-Match,
It works for other URL links
Things I had to try:
Is adding a name in project URL
including URL path in my App URL
My project URL code:
from Django.contrib import admin
from django.urls import path, include
urlpatterns = [
path(r'admin/', admin.site.urls, name='admin' ),
path(r'accounts/', include('django.contrib.auth.urls')),
path(r'api-auth/', include('rest_framework.urls'), name='rest_framework'),
path(r'', include('app.urls')),
My App URL code:
from django.urls import path, include
from . import views #function views
from django.contrib.auth.decorators import login_required, permission_required
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'tank', views.TankViewSet)
router.register(r'room', views.RoomViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path(r'',login_required(views.index), name='index'),
path (r'test/',views.Test),
path(r'^Water/',login_required(views.Lquid), name='tank'),
path(r'^Ambient/',login_required(views.Ambient), name='room'),
path(r'Rest-api/', include(router.urls)),
#path(r'admin/', admin.site.urls, name='admin' ), this somthing I had try
]
Basically, Django makes in a way that works and redirect to the URL link on any page
NAVBAR:
Admin site
App URL:
path(r'',login_required(views.index), name='index'),
With this two link it will redricet to the page you set.
Apprentice if you cold help
You need to specify the admin page you want to redirect to when doing a reverse lookup of admin. To get to the admin homepage you will want this reverse lookup
reverse('admin:index')
So to link to the admin homepage in your nav bar, it should look like this
<a class="nav-link" href="{% url 'admin:index' %}"> Admin site </a>
Check out the docs on how to reverse lookup admin pages

Redirect to /admin/auth/user/ since my Django app

I'm looking for add a new reverse url in order to redirect to /admin/auth/user/ in my Django Admin page.
In my template, I already have : href="{% url "admin:index" %}" line which let to overcome to the admin page.
I would like to go directly to the users manage page and groups manage page respectively admin/auth/user/ and admin/auth/group.
My urls.py file looks like :
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name=os.path.join(settings.BASE_DIR, 'Accueil/templates/Choice.html')),
name='choice'),
url(r'^admin/', admin.site.urls),
url(r'^Identity/', include('Identity.urls')),
url(r'^Accueil/', include('Accueil.urls')),
url(r'^Home/', include('log.urls')),
url(r'^Informations/', include('Informations.urls')),
url(r'^Configurations/', include('Configurations.urls')),
url(r'^__debug__/', include(debug_toolbar.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
How I can write href="{% url "admin:index" %}" in order to add user and group ? Up to now, I don't find a way to do that.
Thank you by advance
You can reverse the user and group changelist urls with:
{% url "admin:auth_user_changelist" %}
{% url "admin:auth_group_changelist" %}
See the docs on reversing admin urls for more info.

Django URL namespaces - the template has to know its namespace?

I've been tinkering with (my first) Django project that started out with Django 1.6 and has just recently moved to Django 1.8. I've also been working through Django Patterns & Best Practices, learning how I should have structured it all along :-)
My project has several sub-apps and a typical main urls.py with lines like:
(r'', include('noc.apps.frontpage.urls')),
Within each app, I've prefixed all the URL names with the app name, e.g. frontpage_edit_page and used {% url %} throughout the templates to refer between views.
Then I read about URL namespaces, and thought I could de-uglify my URL names. As I first interpreted it, if I added a namespace to each include() in the main urls.py, everything would function as before, because the URL names referred to would all be resolved by the 'local' app. But it doesn't seem to work that way.
With this in the main urls.py:
(r'', include('noc.apps.frontpage.urls', namespace='frontpage', app_name='frontpage')),
This in the app urls.py:
url(r'^frontpage/edit/(?P<slug>[A-Za-z0-9]+)$', views.edit_page, name='front_page_edit_page'),
and {% url 'front_page_edit_page' slug=page.slug %} in a template inside that app, I get a NoReverseMatch exception with 0 URLs tried.
All the examples I can find are talking about prefixing URLs with the namespace - frontpage:front_page_edit_page but 1) how is this an improvement on the previous app prefix on the URL name? and 2) how could you ever have two instances of the same app, which is supposed to be a benefit... So I'm assuming that this is for linking between apps, not within apps.
So what is it that I am missing? Do I need to embed the app_name or namespace in my view function too? It's true that if I do prefix all my URL names with the namespace, even within the app, I get a rendered page, but it seems to defeat the point.
The way you're meant to do it is indeed to add the namespace to the URL tag;
{% url 'frontpage:edit_page' slug='SLUG' %}
But it would be better practice to structure your main project URls file like this;
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'frontpage', include('noc.apps.frontpage.urls', namespace='frontpage', app_name='frontpage')),
That way you can specify the path for each app in the main URLs file, and avoid repetition;
urlpatterns = patterns(
'noc.apps.frontpage.views',
url(r'^edit/(?P<slug>[A-Za-z0-9]+)$', 'edit_page', name='edit_page'),
With this you can introduce a RESTful URL structure to all your apps so you'll end up with things like;
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'frontpage/', include('noc.apps.frontpage.urls', namespace='frontpage', app_name='frontpage')),
url(r'contact/', include('noc.apps.contact.urls', namespace='contact', app_name='contact')),
url(r'myapp/', include('noc.apps.myapp.urls', namespace='myapp', app_name='myapp')),
All your apps can follow a similar structure then;
urlpatterns = patterns(
'noc.apps.contact.views',
url(r'^$', 'index', name='index'),
url(r'^add/$', 'add', name='add'),
url(r'^edit/(?P<slug>[A-Za-z0-9]+)$', 'edit', name='edit'),
urlpatterns = patterns(
'noc.apps.myapp.views',
url(r'^$', 'index', name='index'),
url(r'^add/$', 'add', name='add'),
url(r'^edit/(?P<slug>[A-Za-z0-9]+)$', 'edit', name='edit'),
Multiple instances of frontpage could be achieved using the top level namespace;
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'frontpage/', include('noc.apps.frontpage.urls', namespace='frontpage1', app_name='frontpage')),
url(r'frontpage/', include('noc.apps.frontpage.urls', namespace='frontpage2', app_name='frontpage')),
That way you should be able to target the top level instance namespace, followed by the app namespace like this;
{% url 'frontpage1:frontpage:edit_page' slug='SLUG' %}
{% url 'frontpage2:frontpage:edit_page' slug='SLUG' %}
But if you would like to keep your template links more generic I believe you can leave out the top level namespace and django will resolve to the current app which you have to add to the request object. This is detailed at the end of Reversing Namespaced URLs
For anyone to reference.
This worked for me, Django 2.2.2
# project urls.py
# DjpollsConfig is my app config
from djpolls.apps import DjpollsConfig
djpolls_app_name = DjpollsConfig.name
urlpatterns = [
path(djpolls_app_name, include('djpolls.urls', namespace='djpolls_app_name'))
]
# app urls.py
from django_proj.urls import djpolls_app_name
app_name = djpolls_app_name
# app template
{% url 'djpolls_app_name:detail' question.id %}
Hope it helps!
Try this
(r'', include('noc.apps.frontpage.urls', namespace = 'abc')),
and then in your templates:
{% url 'abc:frontpage:front_page_edit_page' slug=page.slug %}