VS2019 development Django (eight) ------ View

Navigation: VS2019 series Django development

 

About Django, I am also the initial contact, as it is a study notes, have to understand the place is not in place or wrong, please correct me -

Django official document: https://docs.djangoproject.com/zh-hans/2.1/

Django Web framework in Visual Studio: https://docs.microsoft.com/zh-cn/visualstudio/python/learn-django-in-visual-studio-step-01-project-and-solution?view=vs- 2019

 

These days learning about Django views and templates, from a few days to learn the progress of view, the view here and not spend a lot of time, on the contrary, template spent a lot of time, the main reason is because Jquery dom does not operate skilled, followed by the use of the bootstrap unskilled, so I spent some time researching official documents.

So, get down to business, starting with the view (views.py) start with. In Django view Unlike other frameworks view (especially the MVC pattern), Django in view, with Asp.Net Mvc framework analogy, is the Controller, inside view function is Action, the In the second blog post introduction file directory structure when there are mentioned, then our request, to reach a controller, and then reach a Action, requires a routing table, Django is also a similar design, but changed the statement, called the URL scheduler , specific usage we can see the official document, the document will introduce a lot of matching rules, complicated regular expressions can be used to configure the matching rules, but experience tells me that this routing rule is as straightforward as possible is good, because if it is not Api open to a third party, then, with this rule, after all, themselves, in turn, even if it is open to a third party Api, too complicated people will be criticized. Of course this is just my personal opinion ......

Next, it was time directly on the code, look DjangoLazyOrders this project, my URL configuration is how to configure: divided into two parts, one is the URL of the entire application configuration, a hello is this App the URL configuration, focus looking at the color of the code.

#D:\项目\local\DjangoLazyOrders\DjangoLazyOrders\urls.py
urlpatterns = [path('', views.home, name='home'),
    path('contact/', views.contact, name='contact'),
    path('about/', views.about, name='about'),
    path('login/',
         LoginView.as_view(template_name='app/login.html',
             authentication_form=forms.BootstrapAuthenticationForm,
             extra_context=
             {
                 'title': 'Log in',
                 'year' : datetime.now().year,
             }),
         name='login'),
    path('logout/', LogoutView.as_view(next_page='/'), name='logout'),
    path('admin/', admin.site.urls),
    path('hello/', include('hello.urls')),]
from django.urls import path,include
from hello import views

#D:\项目\local\DjangoLazyOrders\hello\urls.py
urlpatterns = [path('hello/',views.hello,name='hello'),
               path('test/',views.test,name='test'),
               path('lazy_orders_index/',views.lazy_orders_index,name='lazy_orders_index'),
               path('<int:category_id>/category/', include([path('delete/', views.category_delete,name='category_delete'),path('edit/', views.category_edit,name='category_edit')]))]

So, what the rules of the code above represent it?

1) hello \ urls.py configuration shows a total of three views, namely lazy_orders_index, category_delete, category_edit, then, these three views respectively corresponding to the view function how to define it? Direct look at the code (not part of the code to achieve full):

  • lazy_orders_index request parameter is required with all the view function the first argument is always the request, because the first parameter is not configured routing rules, only the default parameters
  • category_delete, category_edity have a common portion <int: category_id>, delete and edit a parameter required category_id, so the extracted common part to the front, and then matching each respective rules, delete and edit
import json
from datetime import datetime
from django.core import serializers
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from hello.models import Category,Menu

# Create your views here.
def hello(request):
    return HttpResponse("hello world!")

def test(request):
    return HttpResponse("test")

DEF category_edit (Request, category_id):
     return HttpResponse ( " Edit " ) 

DEF lazy_orders_index (Request): 
    categorys = Category.objects.all () # query all categories 
    Menus = Menu.objects.all () # query all menu 

    json_categorys = [] # define two arrays used to store the data model of json 
    json_menus = [] 

    for category in categorys: 
        json_categorys.append ({ 
        " category_id " : category.category_id,
          " category_name ":category.category_name#遍历实体对象 构建ViewModel的数据
         })

    for menu in menus:
        json_menus.append({
            "category_name":menu.category.category_name,
            "menu_name":menu.menu_name
            })

    context = {'json_categorys': json.dumps(json_categorys),'json_menus':json.dumps(json_menus),'categorys':categorys,'menus':menus,'year':. DateTime.Now ()} year
     return render (Request, ' Hello / lazyorders.cshtml ' , context) # The data and template into html rendering function passed to render back to the client 

DEF category_delete (Request, category_id): 
    the Category. objects.get (PK = category_id) .Delete ()
     return jsonResponse ({ ' code ' : 0, ' Message ' : ' OK ' })

 

2) Django built-in shortcut function

  • the render (), given template with a given context dictionary together, and returns to render a text HttpResponseobject. The popular thing is to pass a request object, and specify the template, and templates to use data to this function, the function template will be rendered into a standard html text, and then returned to the browser.
  • redirect (), a HttpResponseRedirectreturn to the appropriate URL arguments passed. The popular thing is to jump to the specified URL.

We have used the above View into the render () function template specifies lazyOrders.cshtml files in the hello App (suffix reason for the .cshtml an explanation has been done), the data object context, context I both check directly to the entity object from the database, but also encapsulates a ViewModel json data passed to the template, why is that? Because I want to achieve two sets of logic in the template, the next template related content will be described in detail, just mention here.

 

 3) JsonResponse ()

  • To return the data to the frontend Json, the HttpResponse may be used, and specify the content-type of application json / to, the following sample code:
    def test(request):
        data = {
        'name': 'dengwei',
        'sex': ''
        }
        return HttpResponse(json.dumps(data),content_type="application/json")

  • In addition to the above-described method, Django also provides a more convenient http response class, jsonResponse, for this class source code can be known, inherited from HttpRespons, and internal data calls json.dumps () of the sequence, also found this class requires the object must be serialized dict type of object, if the object to be serialized non dict must pass safe parameter is false, the default is true
    class JsonResponse(HttpResponse):
        """
        An HTTP response class that consumes data to be serialized to JSON.
    
        :param data: Data to be dumped into json. By default only ``dict`` objects
          are allowed to be passed due to a security flaw before EcmaScript 5. See
          the ``safe`` parameter for more information.
        :param encoder: Should be a json encoder class. Defaults to
          ``django.core.serializers.json.DjangoJSONEncoder``.
        :param safe: Controls if only ``dict`` objects may be serialized. Defaults
          to ``True``.
        :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
        """
    
        def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                     json_dumps_params=None, **kwargs):
            if safe and not isinstance(data, dict):
                raise TypeError(
                    'In order to allow non-dict objects to be serialized set the '
                    'safe parameter to False.'
                )
            if json_dumps_params is None:
                json_dumps_params = {}
            kwargs.setdefault('content_type', 'application/json')
            data = json.dumps(data, cls=encoder, **json_dumps_params)
            super().__init__(content=data, **kwargs)
  • Do the following test for the object type of non-dict: 
    def test(request):
        #data = {
        #'name': 'dengwei',
        #'sex': '男'
        #}
    
        data = [{
        'name': 'dengwei',
        'sex': ''
        },{
        'name': '女帝',
        'sex': ''
        }]
        
        
        return JsonResponse(data)

  • After the increase safe parameter assignment is false, test again, return to normal

    def test(request):
        #data = {
        #'name': 'dengwei',
        #'sex': '男'
        #}
    
        data = [{
        'name': 'dengwei',
        'sex': ''
        },{
        'name': '女帝',
        'sex': ''
        }]
        
        
        return JsonResponse(data,safe=False)

Guess you like

Origin www.cnblogs.com/dwBurning/p/Django8.html