1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Django Girls Tutorial のアップグレード Django 1.11 → 2.0の変更点

Last updated at Posted at 2018-10-08

#経緯
Django Girls Tutorialをやり遂げてGithubで管理していたところ、警告メッセージが届いてしまいました。

ebichiki,

We found a potential security vulnerability in a repository for which you have been granted security alert access.

ebichiki/djangogirls
Known moderate severity security vulnerability detected in django >= 1.11.0, < 1.11.15 defined in requirements.txt.
requirements.txt update suggested: django ~> 1.11.15.

脆弱性が発見されたとのことで、Djangoのバーションが古いようです。
新しいチュートリアルが存在したのでアップグレートしました。
旧:https://djangogirlsjapan.gitbooks.io/workshop_tutorialjp/content/
新:https://tutorial.djangogirls.org/ja/

#Django 1.11 → 2.0の変更点

ForeignKey制約の記述

参照するオブジェクトが削除された時に、それらと紐付けされたオブジェクトの振る舞いをどうするかを設定します。チュートリアルでは、on_delete=models.CASCADEで一緒に削除するようになっています。

Django 1.11

blog/models.py
from django.db import models
from django.utils import timezone

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

Django 2.0

blog/models.py
from django.db import models
from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

##urlの設定
Path関数で指定します。正規表現を使わないので簡単に記述できるようになりました。

###Django 1.11

mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'', include('blog.urls')),
]

###Django 2.0

mysite/urls.py
from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?