Djangoを使用した食料品袋(パート1)—導入とプロジェクトセットアップ



導入
食料品店は、マーケティングのために食料品アイテムを保存する方法です.これは、購入し、すでに購入アイテムのすべてのリストを表示されるホームページが含まれます.ユーザーがアイテムを追加し、アイテムを更新し、さらにそれらを削除することができます.


要件
  • ユーザーは自分自身を登録することができますログイン/ログアウトシステムがあります.
  • ユーザーを購入する食料品のリストを作成することができます.
  • のようなフラグを作成-購入、左と利用できません
  • 保存されたリストを表示するには、バーを作成し、ホームページには、日付に応じてすべてのリストが表示されます.
  • スクリーンショット
    いくつかのスクリーンショットを与えられた以下のあなたは私たちが構築しているのアイデアを与える.

    インデックスページ

    新規アイテム追加

    アイテムを更新する


    プロジェクト設定
    プロジェクトのセットアップを始める前に、システムにPythonをインストールしておいてください.次のコマンドで確認できます.
    $ python
    Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 
    
    
    上記の出力を取得したら、Pythonをインストールします.ない場合は、からダウンロードすることができますthis page .
    我々は、仮想環境を使用しますenv 我々のプロジェクトのために.環境を作りましょう
    $ python -m venv env
    
    注:使用することができますpython3 …の代わりにpython あなたの要件ごとに.
    環境を有効にするには、次のコマンドを使用します.
  • Windowsでは、次のコマンドを実行します.
  • $ env\Scripts\activate.bat
    
  • UnixやMacOSでは、次のコマンドを実行します.
  • $ source env/Scripts/activate
    
    仮想環境がアクティブになったので、以下のコマンドを使用して必要なライブラリをインストールできます.
    $ pip install Django
    
    上記のコマンドは、仮想環境にdjangoをインストールします.今、我々は我々のdjangoプロジェクトを作成する準備ができていますGroceryBag . 次のコマンドを実行して、プロジェクトを現在のディレクトリに作成します.
    $ django-admin startproject GroceryBag .
    
    今、要件ごとに、我々は2つのアプリが必要ですbag 食料品袋の上のcrud操作を取り扱うために、そしてaccounts 認証を処理するにはつずつこれらのアプリを作成してみましょう.
    $ python manage.py startapp bag
    $ python manage.py startapp accounts
    
    つのアプリが作成された後、別の作成urls.py 両方のアプリケーションディレクトリのファイルを、両方のファイルに次のコンテンツを追加します.
    from django.urls import path
    
    urlpatterns = [
    
    ]
    
    
    それから、我々は我々のプロジェクトでこれらの2つのアプリを登録する必要があります.だから、オープンsettings.py 食料品店のディレクトリではINSTALLED_APPS リスト.
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        # Your apps below
        'accounts', 
        'bag',
    ]
    
    プロジェクトの後期では、無料のクラウドプラットフォームに配備されます.そこで、環境変数を設定する必要があります.Pythonのdecoupleを使って、私たちを助けましょう.
    $ pip install python-decouple
    
    インストールしたらファイルを作ります.env カレントディレクトリで次のコンテンツを追加します.
    
    SECRET_KEY=django-insecure-6wx#%@2ift=4@1(*eiw5n&rh!5t!bytp6=#8viz^$ola#p5nsm
    DEBUG=True
    
    
    今、私たちは、いくつかの変更を加える必要がありますsettings.py ファイル.それらを作りましょう
    """
    Django settings for GroceryBag project.
    
    Generated by 'django-admin startproject' using Django 3.2.9.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/3.2/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/3.2/ref/settings/
    """
    
    from pathlib import Path
    from decouple import config
    
    # Build paths inside the project like this: BASE_DIR / 'subdir'.
    BASE_DIR = Path( __file__ ).resolve().parent.parent
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = config('SECRET_KEY') # Get value from environment variables
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = config('DEBUG') # Get value from environment variables
    
    ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # Add these two for now
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        # Your apps below
        'accounts', 
        'bag',
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    ROOT_URLCONF = 'GroceryBag.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [BASE_DIR / 'templates'], # Add the templates directory
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'GroceryBag.wsgi.application'
    
    # Database
    # https://docs.djangoproject.com/en/3.2/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
    
    # Password validation
    # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    # Internationalization
    # https://docs.djangoproject.com/en/3.2/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/3.2/howto/static-files/
    
    STATIC_URL = '/static/'
    STATIC_ROOT = BASE_DIR / 'staticfiles'
    
    STATICFILES_DIRS = [
        BASE_DIR / "static",
    ]
    
    # Default primary key field type
    # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
    
    DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
    
    
    上記のファイルでは、テンプレートと静的ディレクトリに関する重要な変更をしました.
    この後、templates ディレクトリとstatic HTMLファイルと静的ファイル(CSS、JavaScript、イメージ)の現在のディレクトリのディレクトリ.静的フォルダーの中でcss すべてのCSSファイルが保存されます.
    HTMLテンプレートとCSSファイルをダウンロードhere そして、それぞれのディレクトリに追加します.
    さて、オープンGroceryBag/urls.py ファイルを変更し、以下のように変更します.
    from django.contrib import admin
    from django.urls import path, include
    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('bag.urls')),
        path('accounts/', include('accounts.urls')),
    ]
    
    if settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL,
                              document_root=settings.STATIC_ROOT)
    
    
    上記のスクリプトでは、我々はbag and accounts アプリ.また、我々は提供する予定です静的ファイルのURLパターンを作成しました.
    次のコマンドを使用してデータベースを移行する必要があります.
    $ python manage.py migrate
    
    コマンドを実行すると、いくつかの出力が表示されます.それが完了したら、あなたはdb.sqlite3 カレントディレクトリのファイル.これは、我々のデータベースが正常に移行されていることを示します.
    さて、以下のようにサーバを走らせることができます.
    $ python manage.py runserver
    
    サーバーを実行すると、コンソールにURLが表示されます.お気に入りのブラウザで開き、同様の出力が表示されます.

    今このエラーを心配しないでください.それは、それを見つけることができません/ ルート次のブログでこれを解決します.これにより、プロジェクトのセットアップが完了しました.現在までのディレクトリ構造にマッチできます.
    .
    ├── GroceryBag
    │   ├── __init__.py
    │   ├── asgi.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    ├── accounts
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── migrations
    │   │   └── __init__.py
    │   ├── models.py
    │   ├── tests.py
    │   ├── urls.py
    │   └── views.py
    ├── bag
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── migrations
    │   │   └── __init__.py
    │   ├── models.py
    │   ├── tests.py
    │   ├── urls.py
    │   └── views.py
    ├── db.sqlite3
    ├── manage.py
    ├── static
    │   └── css
    │   └── style.css
    └── templates
        ├── add.html
        ├── index.html
        └── update.html
    
    

    結論
    このブログでは、このプロジェクトで何を築こうとしているかを理解しています.また、プロジェクトを設定します.次のブログでは、プロジェクトに取り組んでいきます.ステイ!
    今までコードhttps://github.com/ashutoshkrris/Grocery-Bag/tree/blog1