django 常用清单

views.py 常用

from django.http import HttpResponse,JsonResponse

Request对象

request.GET
request.POST
request.body.decode("utf-8")
from django.shortcuts import render
render(request,templatename)

Response对象

HttpResponse


return HttpResponse("hello world!")

JsonResponse对象


    return JsonResponse({"name": "lsl"})
    from django.shortcuts import render_to_response
    return render_to_response('myapp/index.html', {"foo": "bar"},
    content_type="application/xhtml+xml")

其他

csrf

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

cache

from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect

@cache_page(60 * 15)
@csrf_protect
def my_view(request):
    # ...

urls.py


from django.conf.urls import include, url
from .views import SS

urlpatterns = [
    url("/ss", SS, name="SS")
]


models.py


from django.db import models

class People(models.Model):
    name = models.CharFields(max_length=32, verbose_name="lsl")
    passwd = models.CharFields(max_length=32, verbose_name="passwd",
    blank=True,null=True)
    city = models.ForeignKey("City")


class City(models.Model):
    name = models.CharFields(max_length=32, verbose_name="城市名称")


blank 是否允许为空
null 是为允许为空值
verbose_name 显示在admin后台上

auto_now 当对它操作时为会自动更新
auto_add_now 当插入时自动更新为现在


forms.py



from django import forms
from .models import People

class PeopleForm(forms.Model):
    class Meta:
        model = People

class CityForm(forms.forms):
    name = forms.CharField(max_length=100)
    title = forms.CharField(max_length=3,
                widget=forms.Select(choices=TITLE_CHOICES))
    birth_date = forms.DateField(required=False)


form.errors  -> 字符串
forms.errors.as_data() ->数据


admin.py


from django.contrib import admin

class modelAdmin(admin.ModelAdmin):
    list_display =[]
    fields = []
    filter_list = []
    search_fields = []

admin.site.register(model, modelAdmin)


tests.py


from django.test import TestCase


class FooTestCase(TestCase):
    def setUp(self):
        pass
    def tearDown(self):
        pass
    def test_foo(self):
        pass


Loading Disqus comments...
Table of Contents