Reputation: 57
I have two apps called shop and subapp_gallery . Basically, subapp_gallery contains photo albums.. In my shop app I have my homepage for the website. so how can I redirect from link in a homepage[links to each albums] to subapp_gallery's albums path.both apps are working without errors. Thanks in advance.
--image attached down--
>shop_project
>>settings.py
>>urls.py
>shop
>>apps.py
>>models.py
>>urls.py
>>views.py
>subapp_gallery
>>apps.py
>>models.py
>>urls.py
>>views.py
This is urls.py file in shop app >>
from django.urls import path
from . import views
urlpatterns = [
path('', views.shop, name='shop-home'),
path('about', views.about, name='shop-about'),
path('pricing', views.pricing, name='shop-pricing'),
]
This is urls.py file in subapp_gallery app >>
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<topic_name>\w+)/$', views.topic, name='topic'),
url(r'^(?P<topic_name>\w+)/(?P<photo_id>[0-9]+)/$', views.detail, name='detail')
]
Upvotes: 1
Views: 5006
Reputation: 11
For anyone who will need this.If you have two apps ,shop and sub_gallery, and you need a view in shop.views.py to redirect to a view of the other app, here's what you can do:
Assuming:
1.The the view for redirecting is called redirect_view
2.This view takes one arg(int)
3.Name of the url in sub_gallery.url.py is redirect_view:
#In shop.views.py:
from django.http import HttpResponseRedirect
from django.urls import reverse
....
#the view that redirects to sub_gallery app
def redirect_view(request):
return HttpResponseRedirect(reverse('sub_gallery:redirect_view',args=(1',))
#In shop.urls.py:
...
from sub_gallery.views import receiving_view
app_name='shop'
urlpatterns=[
...
path('redirect_view/<int:number>/',receiving_view,name='receiving_view'),
#In sub_gallery.urls.py:
app_name='sub_gallery'
...
urlpatterns=[
...
path('receiving_view/<int:number>/',views.receiving_view,name='receiving_view')
]
#In sub_gallery.views.py
....
from django.shortcuts import render
def receiving_view(request,number):
context={'dummy':number}
return render(request,'somefile.html',context)
Note that my directory structure is:
->shop
->sub_gallery
not
->shop/sub_gallery.
Just do some modifications and it'll work.
With DEBUG=False, you'll see the redirection.
Upvotes: 1
Reputation: 57
It's silly question. just used "{% url 'topic' %}"and It worked. django is smart enough to know which name from which application.
Upvotes: 2
Reputation: 2484
You're looking for naming url patterns
You can use reverse('<namespace>:<urlname>')
to get the url you want to redirect to.
Upvotes: 0