[Django]-How to create href link from one Django app to another

2👍

in your template and views try not to hardcode the url of href instead use the {%url ''%}
which will be {%url 'namespace:urlname'%}

<p>This is the template of app1.</p>
<a href="{% url 'app2:app2'%}">Go to App2</a>

this give you flexibility to change the path in your urls and not to worry about changing it at all your templates and views you can read more here https://docs.djangoproject.com/en/3.1/topics/http/urls/#reverse-resolution-of-urls

👤seif

2👍

your href link doesn’t go to the .html file in templates, templates are just for UI, and barely have a say in how you project gets routed, infact it depends on you to configure. instead it should go to the url specified in your url file,

so say your bases url is

path('app1/', include('app1.urls'), name='app1')

for one of your app it will be

<a href="example.com/app1">App 1</a>

if you have other links under app1 url file, it will then be

<a href="example.com/app1/myother-app1-link">A link under App 1</a>

example.com here, could be localhost:8000 or just localhost with any port, depending on the port your django project runs one.

then as for this,

from django.template import loader
from django.http import HttpResponse

def app1(request):
    template = loader.get_template('app1/app1.html')
    return HttpResponse(template.render())

I will suggest you do something like this instead

from django.shortcuts import render
from django.http import HttpResponse, HttpRequest

def app1(request,slug=None):
    return render(request,'app1/app1.html',{})
    #path to the template folder, under templates, depends on your configuration though

Kindly read more on templates configuration and routing in Django,but this should give a jumpstart.

Cheers

0👍

When you input "127.0.0.1:8000/app1/app2/", django will recieve "app1/app2/" and work like below(not accurate):

1.compare app1/ to every element in urlpatterns of myproject/urls.py

so, app1/ will be found.

2.compare app2/ to every element in urlpatterns of app1.urls

there’s nothing will be found, because there is only a "" in urlpatterns of app1.urls.

so you get a 404 page.

if you input "127.0.0.1:8000/app2/", in step 2, "" equals to "",

fuction views.app2 executes, and you get a correct page.

I suggest you read the django’s tutorials in official site.

https://docs.djangoproject.com/en/3.1/intro/tutorial01/

Leave a comment