Django使用笔记(一)

Django是Python语言编写的一个全栈式Web框架,使用它我们可以快速实现一个具有简单功能的网站。和其它web框架一样,Django也采用MVC模式。以下内容是笔者在使用Django的过程中接触到的地方,更多信息可以从官方文档中获取。

特别强调:
Django版本为1.9.5,Python版本为3.5
不同版本之间有差异,如有问题,以实际使用版本为准

安装Django

安装Django的方式非常简单,直接通过pip进行安装:

pip install django
  1. 使用django更改models后,依次执行如下命令:
python manage.py makemigrations
python manage.py migrate
  1. django.shortcuts里有一些函数,使用它们可以减少代码量,例如:
    不使用这些shortcuts,编码可能如下:
from django.http import Http404
from django.shortcuts import render
from .models import Question
def detail(request, question_id):
	try:
		question = Question.objects.get(pk=question_id)
	except Question.DoesNotExist:
		raise Http404("Question does not exist")
	return render(request, 'polls/detail.html', {'question': question})

使用shortcuts里的get_object_or_404()后,编码如下:

from django.shortcuts import get_object_or_404, render
from .models import Question
def detail(request, question_id):
	question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})
  1. 实现表之间的关系:
  • 多对一:models.ForeignKey
  • 多对多:models.ManyToManyField
  • 一对一:models.OneToOneField
  1. 在Django中,把公共属性放在一个类里,由子类继承并且创建对应的数据库表,做法如下:
from django.db import models
class CommonInfo(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()
        class Meta:
            abstract = True
class Student(CommonInfo):
    home_group = models.CharField(max_length=5)
  1. 同一个url,不管请求方法是什么,它都将被路由到同一个view function中
    要限制请求方式,可在view function上加@require_http_methods,添加请求方式
  2. middleware 定义在 settings.pyMIDDLEWARE_CLASSES 中,其执行顺序是:
  • 请求阶段:自顶向下
  • 响应阶段:自底向上
  1. 编写自定义的 middleware 时,一般定义如下方法:
  • process_request(request)
  • process_view(request, view_func, view_args, view_kwargs)
  • process_template_response(request, response)
  • process_response(request, response)
  • process_exception(request, exception)
  1. 验证客户端是否接受cookies的方法如下:
from django.http import HttpResponse
from django.shortcuts import render
def login(request):
    if request.method == 'POST':
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()
            return HttpResponse("You're logged in.")
        else:
            return HttpResponse("Please enable cookies and try again.")
    request.session.set_test_cookie()
    return render(request, 'foo/login_form.html')
  1. pythonjson包不支持序列化djangomodels里的对象实例,而django.core.serializers又只能序列化QuerySet对象,因此要序列化一个具体的models实例,可以采用如下方法:
class Reporter(models.Model):
    full_name = models.CharField(max_length=70)

    def __str__(self):
        return self.full_name

    def toJSON(self):
        import json
        from django.core.serializers.json import DjangoJSONEncoder
        return json.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]),cls=DjangoJSONEncoder)

其中指定了json.dumpscls参数,这样json.dumps才能支持特殊类型(如datetime.date)的json转换。
不过这段代码在model包含外键关联的时候就不适用了,因为它包含另一个model了。

  1. 使用JsonResponse(data)时,如果传入的data对象不是dic类型,需要额外传入safe参数:

JsonResponse(data, safe=False)

猜你喜欢

转载自blog.csdn.net/baidu_30526767/article/details/84452991
今日推荐