How to make dynamic URLs with Django - django

my new project needs to fetch URLs from database. Example:
Backend add Categorys and URLs should work like:
www.example.com/hardware
if I make in Backend a new subcategory:
www.example.com/hardware/notebooks
If I add a article:
ww.example.com/hardware/notebooks/lenovo-e410 or articlenumbers.
But I didnt find out where I can add urls from SQL Queries.

But I didnt find out where I can add urls from SQL Queries.
You don't need to; You should create fixed patterns after your dynamic urls.
So in your urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('/<str:category>/', views.hardware),
path('/<str:category>/<str:subcategory>/', views.subcategory),
path('/<str:category>/<str:subcategory>/<str:article>/', views.areticle),
]
or if you prefer to just have urls for your arricles, remove the first two patterns.
Then in the corresponding views for each pattern, you should look up your database for the urls.

I think you haven't gone through Django tutorial, I request you to go through the tutorial given at https://docs.djangoproject.com/en/3.0/intro/tutorial01/#write-your-first-view
Add the following pattern to urls.py
# urls.py
from django.urls import path
urlpatterns = [
path('/<str:category>/<str:product>/'),
]
# views.py
def product_page_view(request, category, product):
# ... your stuffs
Read about Django URLs at https://docs.djangoproject.com/en/3.0/topics/http/urls/

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.

Change URL for wagtail blog index page

I currently have a website where the home page at www.mysite.com is the wagtail blog index page
I wish to move the blogindex page to another url
I can easily have a different homepage by amending my urls.py file:
#original
path("", include(wagtail_urls))
#new
path(
"",
TemplateView.as_view(template_name="pages/newhomepage.html"),
name="newhomepage",
),
However I would like the blogindex page available at e.g. myste.com/blog but I am not sure how to go about this. Adding the following to urls.py does not do it
path("blog/", include(wagtail_urls))
There are a couple of changes in project required to achieve this.
Firstly, create a urls.py file inside your specific app, this will be different from the one that you should already have alongside wsgi.py, asgi.py, etc. and it will only store app specific urls.
from django.urls import path
from .views import index
urlpatterns = [
path('test/', index, name='generalized-test-url'),
]
Now, you should render the template inside your view.
def index(request):
return render(request, 'pages/newhomepage.html', context)
Lastly, in your root urls.py file, you need to include the app urls. Lets say your app name is blog.
from django.urls import path, include
urlpatterns = [
path('blog/', include('blog.urls')),
]

django urls: "Django tried these URL patterns"

I am trying a tutorial on Django called blog. I have the following structure:
FirstBlog|FirstBlog
settings
urls
__init__
etc
blog
templates | index.html
migrations
views.py
manage.py
The view.py has
from django.shortcuts import render
from django.shortcuts import render_to_response
from blog.models import posts
def home(request):
return render('index.html')
The urls.py has
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
urlpatterns = [
url(r'^blog', 'FirstBlog.blog.views.home',name='home'),
]
and I get this error:
Using the URLconf defined in FirstBlog.urls, Django tried these URL patterns, in this order: ^blog [name='home']
The current URL, , didn't match any of these.
I can't seem to get it right..
Any help would be appreciated.
Thank you,
You are requesting for / url and you have not saved any such mapping. Current mapping is for /blog . So it will work for the same url.
i.e goto the browser and request /blog
If you need it to work for / then change the urls appropriately.
within your blog app, create a urls.py file and add the following code which calls the home view.
blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^',views.home, name='home'),
]
then in your root urls file which can be found at FirstBlog/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^blog/',include('blog.urls')), #when you visit this url, it will go into the blog application and visit the internal urls in the app
]
PS:
your templates should be in blog/templates/blog/index.html
Read this docs on templates to understand how django locates templates.
This one is to understand how urls work Urls dispatcher
You are doing this in the wrong way! Try doing that using TemplateView from class-based views, which are the current standard from django views.
Check the django documentation: https://docs.djangoproject.com/en/1.9/topics/class-based-views/
Use this at the urls.py:
from django.conf.urls import url
from django.views.generic import TemplateView
urlpatterns = [
url(r'^blog/', TemplateView.as_view(template_name="index.html")),
]
And then, create a folder called templates in the project root ( like this: https://docs.djangoproject.com/en/1.9/intro/tutorial03/#write-views-that-actually-do-something ) named index.html
Simply go to file then select Save all your project instead of save. Or use shortcut Ctrl +k s on windows. Project should be able to sync and display the code on Django interface

Recursive URL routing in Django

I want to have a (fairly simple) emulation of SELECT queries through URLs.
For example, in a blogging engine, You'd like /tag/sometag/ to refer to the posts having the sometag tag. Also /tag/sometag/or/tag/other/and/year/2013 should be a valid URL, beside other more complex urls. So, having (theoretically) no limit on the size of the url, I would suggest this should be done recursively, but how could it be handled in Django URL Routing model?
I would use a common URL pattern for all those URLs.
url(r'^query/([\w/]*)/$', 'app.views.view_with_query'),
You would receive all the "tag/sometag/or/tag/other/and/year/2013" as a param for the view.
Then, you can parse the param and extract the info (tag, value, tag, value, year, value) to make the query.
update 2021
django.conf.urls.url is deprecated in version 3.1 and above. Here is the solution for recursive url routing in django:
urls.py
from django.urls import path, re_path
from .views import index
urlpatterns = [
re_path(r'^query/([\w/]*)/$', index, name='index'),
]
views.py
from django.shortcuts import render, HttpResponse
# Create your views here.
def index(request, *args, **kwargs):
print('-----')
print(args)
print(kwargs)
return HttpResponse('<h1>hello world</h1>')
If I call python manage.py run server, and go to 'http://127.0.0.1:8000/query/nice/', I can see these in terminal:
-----
('nice',)
{}
I know this is an old question but for those who reach here in future, starting from django 2.0+, you can use path converter with path to match the path in the url:
# urls.py
urlpatterns = [
path('query/<path:p>/', views.query, name='query'),
]
# views.py
def query(request, p):
# here, p = "tag/sometag/or/tag/other/and/year/2013"
...

Can I have two urls.py with different names?

In Django, is it possible to have two different files with url patterns, neither of which is called urls.py ? Or does Django rely on there being only one set of url patterns per Django app, and that it must be called urls.py ?
I'm using Django CMS and I want to split an app across two apphooks and two menus. So I've tried splitting urls.py into pub_urls.py and train_urls.py but I appear to have broken things by doing that, despite the cms_app.py naming the correct urls - eg:
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
from resources.menu import TrainingMenu, PublicationMenu
class PublicationApp(CMSApp):
name = _("Publication App") # give your app a name, this is required
urls = ["resources.pub_urls"] # link your app to url configuration(s)
menus = [PublicationMenu]
class TrainingApp(CMSApp):
name = _("Training App") # give your app a name, this is required
urls = ["resources.train_urls"] # link your app to url configuration(s)
menus = [TrainingMenu]
apphook_pool.register(PublicationApp) # register your app
apphook_pool.register(TrainingApp) # register your app
Is something like this possible? Or do I have to split this into two different apps?
There is nothing to stop your urls.py simply acting as a way of including multiple other urls files:
urls.py:
from django.conf.urls.defaults import patterns, include
urlpatterns = urlpatterns + patterns('',
(r'^', include('pub_urls')),
(r'^', include('train_urls')))
pub_urls.py:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
(r'^$', 'homeview'),
(r'^stuff/$', 'stuffview')
)
etc.
ROOT_URLCONF in your settings file points to the root url file.
Django doesn't care what your urlpatterns file is called. The default base urlconf is by convention called urls.py, but in fact that's just a setting and can be overridden. After that, you need to explicitly include urlconfs by module name, so again it makes no difference what they're called.
I'm not familiar with Django-CMS and I don't know what it's doing in its CMSApp class, but I suspect you're going to have to dig into that to see what's going on.
It is configurable using ROOT_URLCONF setting.
From django docs
ROOT_URLCONF
A string representing the full Python import path to your root URLconf.
For example: "mydjangoapps.urls". Can be overridden on a per-request basis
by setting the attribute urlconf on the incoming HttpRequest object. See How
Django processes a request for details.
You can also write/get a middleware which can set it appropriately depending upon the host or other parameters in the request.