SoFunction
Updated on 2025-05-14

How to use Django views and URLs routes

In the Django Web framework, views (Views) and URL routing (URL routing) are the core concepts of web application development. Together, they are responsible for mapping user requests to corresponding Python functions and returning appropriate responses.

This article will dive into Django's view and URLs routing system, providing practical code examples and operational guidance, ensuring readers can understand in detail and practical ways how to use these features to build robust web applications.

Detailed explanation of Django view and URLs routing

1. Understand Django Views

A Django view is a Python function that receives a web request and returns a web response. The view function processes data received from the user, interacts with the model (if needed), and returns an HttpResponse object or other type of response containing HTML content.

1. Create a basic view

The first step in creating a view is to define a function. This function needs to receive several specific parameters, usuallyrequestObject plus any number of HTTP methods (such as GET or POST).

from  import HttpResponse

def hello(request):
    return HttpResponse("Hello, World!")

In this example,helloA function is a simple view. When users access the URL associated with the view, they will see the message "Hello, World!".

2. Use a universal view

While views can be written manually to handle common web requests, Django provides a range of common views that can help you quickly implement standard web features such as creation, read, update, and delete (CRUD) operations.

from  import TemplateView

class AboutView(TemplateView):
    template_name = ''

here,AboutViewClass useTemplateViewto present an About page. You just need to specify the name of the template.

3. Advanced usage of view

In more complex applications, we may need to have more granular control over the views, such as processing form data, file uploads, or implementing user-based permission control. Django provides powerful customization capabilities through middleware and class views.

from  import CreateView
from .models import CustomModel

class CustomCreateView(CreateView):
    model = CustomModel
    fields = ['field1', 'field2']

Here,CustomCreateViewInherited fromCreateView, used to handle the creation of a specific model. By specifying the model and fields, you can control which fields are editable by the user.

2. Configure URLs routing

In Django, URLs routing is through the applicationDefine a set of URL patterns in the file to implement it. These patterns determine which view should respond to which URL request. Let's dive deeper into how to configure and manage URLs routing to ensure that your application is not only well-structured, but also efficiently directing requests to the correct view.

1. Basic routing configuration

Each URL pattern is mapped to a view function, which can be usedpath()Function orre_path()(Regular expressions are supported) to complete.

from  import path
from . import views

urlpatterns = [
    path('hello/', , name='hello'),
]

A path is defined herehello/, it will be mapped toview. By specifyingnameParameters, you can use this name in templates and elsewhere to refer to this URL pattern.

Dynamic routing parameters

Routers can also accept dynamic parameters, such as:

path('user/<str:username>/', , name='user_profile'),

In this example,<str:username>is a dynamic field of string type, and this URL will match like/user/johndoe/Such a URL and willjohndoeAsusernameParameters passed tofunction.

2. Advanced routing technology

For more complex applications, you can use Django's advanced routing technology, including using view classes, view sets, and nested routing.

1. Use view classes

View classes provide a more structured way to manage URL routing and view logic.

from  import re_path
from .views import AboutView

urlpatterns = [
    re_path(r'^about/$', AboutView.as_view(), name='about'),
]

here,AboutViewInstantiation of the class isAboutView.as_view()Completed and passedre_pathAssociated with URL pattern.

2. Use view sets

ViewSets provides a collection of APIs that can be reused in multiple URLs.

from rest_framework.routers import DefaultRouter
from .views import MyModelViewSet

router = DefaultRouter()
(r'models', MyModelViewSet)

urlpatterns = 

In this example, we used the Django REST framework's router to automatically perform ourMyModelViewSetGenerate CRUD-related URL patterns.

3. Nested lane order

Django also supports nested route commands, which are very helpful for building URLs with hierarchical structures. Suppose you are building a blog application, you may use the following nested routing configuration:

from  import include, path
from .views import blog_views

urlpatterns = [
    path('blog/', include([
        path('post/', blog_views.post_list, name='post-list'),
        path('post/<int:year>/', blog_views.post_year, name='post-year'),
        path('post/new/', blog_views.post_new, name='post-new'),
        path('post/<int:pk>/edit/', blog_views.post_edit, name='post-edit'),
        path('post/<int:pk>/remove/', blog_views.post_remove, name='post-remove'),
    ])),
]

In this configuration, all/blog/The URLs at the beginning will beincludeFunction capture, and then route to the corresponding view according to subsequent URL fragments. This method can clearly organize the code and keep the URLs structure neat.

By carefully designing and applying these routing configurations, you can ensure that your Django app is not only powerful, but also easy to understand and maintain.

3. Advanced: Use decorators and mix them

In Django, decorators and blending are mechanisms used to extend view functionality. Decorators are a way to enhance function functions without modifying function code. They are usually used in view functions to add functions such as permission verification, cache control, etc. Mixed in, by including specific properties or methods, extending the functionality of the class, provides an alternative method of combining inheritance.

1. Decorators

A decorator is a way to modify the behavior of a function or class without directly changing its code. In Django, decorators are often used to add additional functionality to views, such as checking if the user is logged in.

from  import login_required

@login_required
def profile(request):
    # Logical code...

here,login_requiredDecorators ensure that only logged in users can access itprofileview.

2. Mix in

Mixed in is a form of multiple inheritance that allows you to combine behaviors of multiple classes. In Django, mixing in is often used to reuse view logic.

from  import LoginRequiredMixin
from  import DetailView

class ProfileView(LoginRequiredMixin, DetailView):
    model = User
    template_name = 'user_detail.html'

In this example,ProfileViewThrough inheritanceLoginRequiredMixinandDetailViewTwo behaviors are obtained: the user needs to log in and display the details of a single object.

IV. Security and permissions

In web applications, it is very important to ensure the security of the views. Django provides a range of tools and middleware to help developers achieve this goal.

1. Safety protection

The Django framework comes with a series of security measures, including protection against cross-site request forgery (CSRF), cross-site scripting (XSS), and other web security threats. It is crucial to ensure that each view uses these measures.

from  import csrf_protect

@csrf_protect
def my_view(request):
    # Logical code...

By usingcsrf_protectDecorators, you make sure that the view is protected by CSRF.

2. Permission control

In many applications, some views should be open to users with specific permissions only. Django's permission system can easily implement this requirement.

from  import permission_required

@permission_required('myapp.change_my_model')
def edit_model(request):
    # Logical code...

usepermission_requiredDecorators, you limit onlychange_my_modelOnly users with permission can accessedit_modelview.

V. Testing and debugging

It is very important to ensure that your views and routes work properly during development. Django provides several tools to help you test and debug your code, ensuring the stability and reliability of your application.

1. Unit testing and integration testing

Testing is the key to making sure the code works as expected. Django's testing framework allows you to easily write unit tests and integration tests to validate your views.

from  import TestCase, Client
from .views import hello

class HelloViewTest(TestCase):
    def test_hello(self):
        client = Client()
        response = ('/hello/')
        (response.status_code, 200)
        ((), "Hello, World!")

This code demonstrates how to write a simple test case to testhelloview. Using DjangoClientto simulate sending a request and checking the response.

2. Debugging Tools

When problems arise in development, debugging is a key step in positioning and solving problems. Django has built-in debugging tools to help you track problems and errors.

Running your app in DEBUG mode allows you to obtain detailed error information and stack traces to help you understand the source of the problem. In addition, you can usedjango-extensionsIn the packageRunServerPlusSuch a third-party extension provides an interactive debugger that can go directly to breakpoints in the code for debugging.

3. Test coverage

To ensure that your tests cover enough code, Django can be used with code coverage tools likeintegrated. By measuring test coverage, you can find out which parts of the code are not tested, thus adding more test cases in a targeted manner.

coverage run --source='.'  test
coverage report

With the above commands, you can run tests and view coverage reports, ensuring that every important branch of code is tested.

Summarize

In this article, we have discussed in detail the techniques of setting up and using views, URL routing, and testing and debugging in Django from many aspects. Correct routing configuration is critical to the clarity of the website structure and user experience. We also covered how to ensure code quality by writing unit tests and integration tests, and how to use Django's debugging tools to identify and resolve problems in your code.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.