浏览代码

Project start and app users

kaajavi 5 年之前
父节点
当前提交
fda69d4b77
共有 16 个文件被更改,包括 325 次插入0 次删除
  1. 0 0
      application/__init__.py
  2. 16 0
      application/asgi.py
  3. 133 0
      application/settings.py
  4. 27 0
      application/urls.py
  5. 16 0
      application/wsgi.py
  6. 22 0
      manage.py
  7. 0 0
      users/__init__.py
  8. 3 0
      users/admin.py
  9. 5 0
      users/apps.py
  10. 49 0
      users/managers.py
  11. 0 0
      users/migrations/__init__.py
  12. 23 0
      users/models.py
  13. 10 0
      users/serializers.py
  14. 3 0
      users/tests.py
  15. 5 0
      users/urls.py
  16. 13 0
      users/views.py

+ 0 - 0
application/__init__.py


+ 16 - 0
application/asgi.py

@@ -0,0 +1,16 @@
+"""
+ASGI config for application project.
+
+It exposes the ASGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
+"""
+
+import os
+
+from django.core.asgi import get_asgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')
+
+application = get_asgi_application()

+ 133 - 0
application/settings.py

@@ -0,0 +1,133 @@
+"""
+Django settings for application project.
+
+Generated by 'django-admin startproject' using Django 3.1.3.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/3.1/topics/settings/
+
+For the full list of settings and their values, see
+https://docs.djangoproject.com/en/3.1/ref/settings/
+"""
+
+from pathlib import Path
+
+# 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.1/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = 'd8wx7t%$08@744ad-u(5az(^5l_l5(o3j1&+6_^ndo6mhjttnv'
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+ALLOWED_HOSTS = []
+
+
+# Application definition
+#Django applications
+DJ_APPS = [
+    'django.contrib.admin',
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.messages',
+    'django.contrib.staticfiles',
+]
+#3th part applications
+TP_APPS = [
+    'rest_framework',
+]
+#Work applications
+WT_APPS = [
+    'users',
+    'transactions',
+]
+
+INSTALLED_APPS = DJ_APPS + TP_APPS + WT_APPS
+
+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 = 'application.urls'
+
+TEMPLATES = [
+    {
+        'BACKEND': 'django.template.backends.django.DjangoTemplates',
+        'DIRS': [],
+        '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 = 'application.wsgi.application'
+
+
+# Database
+# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': BASE_DIR / 'db.sqlite3',
+    }
+}
+
+
+# Password validation
+# https://docs.djangoproject.com/en/3.1/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.1/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.1/howto/static-files/
+
+STATIC_URL = '/static/'
+
+AUTH_USER_MODEL = 'users.User'

+ 27 - 0
application/urls.py

@@ -0,0 +1,27 @@
+"""application URL Configuration
+
+The `urlpatterns` list routes URLs to views. For more information please see:
+    https://docs.djangoproject.com/en/3.1/topics/http/urls/
+Examples:
+Function views
+    1. Add an import:  from my_app import views
+    2. Add a URL to urlpatterns:  path('', views.home, name='home')
+Class-based views
+    1. Add an import:  from other_app.views import Home
+    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
+Including another URLconf
+    1. Import the include() function: from django.urls import include, path
+    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
+"""
+from django.contrib import admin
+from django.urls import include, path
+from users.urls import router as user_router
+
+
+# Wire up our API using automatic URL routing.
+# Additionally, we include login URLs for the browsable API.
+urlpatterns = [
+    path('api/users', include(user_router.urls)),
+    path('admin/', admin.site.urls),
+    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
+]

+ 16 - 0
application/wsgi.py

@@ -0,0 +1,16 @@
+"""
+WSGI config for application project.
+
+It exposes the WSGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
+"""
+
+import os
+
+from django.core.wsgi import get_wsgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')
+
+application = get_wsgi_application()

+ 22 - 0
manage.py

@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+"""Django's command-line utility for administrative tasks."""
+import os
+import sys
+
+
+def main():
+    """Run administrative tasks."""
+    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')
+    try:
+        from django.core.management import execute_from_command_line
+    except ImportError as exc:
+        raise ImportError(
+            "Couldn't import Django. Are you sure it's installed and "
+            "available on your PYTHONPATH environment variable? Did you "
+            "forget to activate a virtual environment?"
+        ) from exc
+    execute_from_command_line(sys.argv)
+
+
+if __name__ == '__main__':
+    main()

+ 0 - 0
users/__init__.py


+ 3 - 0
users/admin.py

@@ -0,0 +1,3 @@
+from django.contrib import admin
+
+# Register your models here.

+ 5 - 0
users/apps.py

@@ -0,0 +1,5 @@
+from django.apps import AppConfig
+
+
+class UsersConfig(AppConfig):
+    name = 'users'

+ 49 - 0
users/managers.py

@@ -0,0 +1,49 @@
+"""
+This module provides class definition to manage Employee objects.
+
+Available classes:
+- EmployeeQuerySet: define a collection of Employee objects.
+- BaseEmployeeManager: interface through which database query operations are
+                       provided to model.
+- PassThroughEmployeeManager: allow to call methods defined in EmployeeQuerySet
+                              from Manager.
+"""
+
+from django.db.models import Manager
+from django.contrib.auth.models import BaseUserManager
+from django.db.models.query import QuerySet
+from django.utils.timezone import now
+
+
+
+
+class UserManager(BaseUserManager):
+    """
+    Interface through which database query operations are provided to
+    Employee model.
+    """
+
+    def _create_user(self, email, password, is_staff, is_superuser,
+                     **extra_fields):
+        """
+        Creates and saves an active User with the given email and password.
+        """
+        if not email:
+            raise ValueError('Users must have an email address')
+        email = self.normalize_email(email)
+        user = self.model(email=email, age=0,
+                          is_staff=is_staff, is_active=True,
+                          is_superuser=is_superuser, **extra_fields)
+        user.set_password(password)
+        user.save(using=self._db)
+        return user
+
+    def create_user(self, email, password=None, **extra_fields):
+        return self._create_user(email, password, False, False,
+                                 **extra_fields)
+
+    def create_superuser(self, email, password, **extra_fields):
+        return self._create_user(email, password, True, True,
+                                 **extra_fields)
+
+

+ 0 - 0
users/migrations/__init__.py


+ 23 - 0
users/models.py

@@ -0,0 +1,23 @@
+from django.db import models
+from django.contrib.auth.models import AbstractUser
+from django.utils.translation import ugettext_lazy as _
+from .managers import UserManager
+
+class User(AbstractUser):
+    """
+        Holds information related to an user.
+    """
+    REQUIRED_FIELDS = []
+    USERNAME_FIELD = 'email'
+
+    objects = UserManager()
+    name = models.CharField(_(u'Name'), max_length=100, blank=True)
+    email = models.EmailField(verbose_name=_(u'Email'),
+                              max_length=255, unique=True,
+                              error_messages={'unique': _('This email already exists')})
+    age = models.PositiveSmallIntegerField(_('Age'), default=None, )
+    is_superuser = models.BooleanField(
+        _('This user is superuser?'), default=False)
+    is_staff = models.BooleanField(
+        _('This user can see the admin panel?'), default=False)
+    is_active = models.BooleanField(_('Is Active'), default=False)

+ 10 - 0
users/serializers.py

@@ -0,0 +1,10 @@
+from rest_framework import serializers
+from django.contrib.auth import get_user_model
+User = get_user_model()
+
+
+class UserSerializer(serializers.HyperlinkedModelSerializer):
+
+    class Meta:
+        model = User
+        fields = ['name', 'email', 'age', 'url']

+ 3 - 0
users/tests.py

@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.

+ 5 - 0
users/urls.py

@@ -0,0 +1,5 @@
+from .views import UserViewSet
+from rest_framework import routers
+
+router = routers.DefaultRouter()
+router.register(r'users', UserViewSet)

+ 13 - 0
users/views.py

@@ -0,0 +1,13 @@
+from rest_framework import viewsets
+from rest_framework import permissions
+from .serializers import UserSerializer
+from django.contrib.auth import get_user_model
+User = get_user_model()
+
+class UserViewSet(viewsets.ModelViewSet):
+    """
+    API endpoint that allows users to be viewed or edited.
+    """
+    queryset = User.objects.all().order_by('-date_joined')
+    serializer_class = UserSerializer
+    permission_classes = [permissions.IsAuthenticated]