Creating Routes

None

ZEBEDEE 5 out of 9
Tip

Creating Routes


Routes are what is used to handle page requests. So for example, when a user tries to go to https://yoursite.com/ it’ll rely upon the index View that is used to render the route / , or the root route. Another example could be https://yoursite.com/success/ , which is what would render the route success using the View success in the Views.py file.


If it’s a bit fuzzy, that’s okay. It’ll make more sense as we work throu

gh the the tutorial. Start by creating a new file in the lightning_address_payment folder called urls.py .




Now paste in the following code. Each item of the urlpatterns points to a function or class in the views.py file located in the lightning_address_payment directory.


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('success/', views.success, name='success'),
]


The next step is to point the root URLconf at the lightning_address_payments.urlsmodule. In lightning_apps/urls.py, add an import for django.urls.include and insert an include() in the urlpatterns list, so you have:


from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('pay_lightning_address/', include('lightning_address_payment.urls')),
    path('admin/', admin.site.urls),
]


This imports all the views we’ll be creating in our other urls.py file.


The include() function allows referencing other URLconfs. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.


The idea behind include() is to make it easy to plug-and-play URLs. Since lightning_address_payment are in their own URLconf (lightning_address_payment**/urls.py**), they can be placed under “/pay_lightning_address/”, or under “/fun_lightning/”, or under “/content/lightningAddress/”, or any other path root, and the app will still work.


Now let’s go ahead and try this out!


Run the following command in your terminal to start the webserver


python3 manage.py runserver



Let’s head to the following URLs to verify our changes worked.

http://127.0.0.1:8000/

http://127.0.0.1:8000/success/



YAY! It worked. Let’s get back to hacking now. This is where the fun begins.

Back Next