用户模型建立,数据库修改为MySql

main
= 3 years ago
parent adb4f2fe44
commit 5907f1e84d

@ -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', 'xxm_oj.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 +1,7 @@
from django.contrib import admin
from .models import User
from .models import UserProfile
# Register your models here.
admin.site.register(User)
admin.site.register(UserProfile)

@ -0,0 +1,6 @@
from django.apps import AppConfig
class UserConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'user'

@ -0,0 +1,41 @@
# Generated by Django 4.1.7 on 2023-03-04 15:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('user_id', models.CharField(max_length=64, primary_key=True, serialize=False)),
('user_name', models.CharField(max_length=64, unique=True)),
('user_password', models.CharField(max_length=64)),
('user_password_confirm', models.CharField(max_length=64)),
('create_time', models.DateTimeField(auto_now_add=True, null=True)),
('user_type', models.CharField(default='Regular User', max_length=20)),
('is_active', models.BooleanField(default=True)),
],
),
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_mail', models.CharField(max_length=64, null=True)),
('real_name', models.TextField(null=True)),
('blog', models.URLField(null=True)),
('mood', models.TextField(null=True)),
('github', models.TextField(null=True)),
('school', models.TextField(null=True)),
('major', models.TextField(null=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='user.user')),
],
),
]

@ -0,0 +1,87 @@
from django.db import models
# Create your models here.
class UserType(object):
REGULAR_USER = "Regular User"
ADMIN = "Admin"
SUPER_ADMIN = "Super Admin"
# class ProblemPermission(object):
# NONE = "None"
# OWN = "Own"
# ALL = "All"
class User(models.Model):
user_id = models.CharField(max_length=64, primary_key=True)
user_name = models.CharField(max_length=64, unique=True)
user_password = models.CharField(max_length=64, null=False)
user_password_confirm = models.CharField(max_length=64, null=False)
create_time = models.DateTimeField(auto_now_add=True, null=True)
user_type = models.CharField(max_length=20,default=UserType.REGULAR_USER)
is_active = models.BooleanField(default=True)
def is_admin(self):
return self.admin_type == UserType.ADMIN
def is_super_admin(self):
return self.admin_type == UserType.SUPER_ADMIN
def is_admin_role(self):
return self.admin_type in [UserType.ADMIN, UserType.SUPER_ADMIN]
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# acm_problems_status examples:
# {
# "problems": {
# "1": {
# "status": JudgeStatus.ACCEPTED,
# "_id": "1000"
# }
# },
# "contest_problems": {
# "1": {
# "status": JudgeStatus.ACCEPTED,
# "_id": "1000"
# }
# }
# }
# acm_problems_status = JSONField(default=dict)
# # like acm_problems_status, merely add "score" field
# oi_problems_status = JSONField(default=dict)
user_mail = models.CharField(max_length=64, null=True)
real_name = models.TextField(null=True)
# avatar = models.TextField(default=f"{settings.AVATAR_URI_PREFIX}/default.png")
blog = models.URLField(null=True)
mood = models.TextField(null=True)
github = models.TextField(null=True)
school = models.TextField(null=True)
major = models.TextField(null=True)
# # for ACM
# accepted_number = models.IntegerField(default=0)
# # for OI
# total_score = models.BigIntegerField(default=0)
# submission_number = models.IntegerField(default=0)
# def add_accepted_problem_number(self):
# self.accepted_number = models.F("accepted_number") + 1
# self.save()
# def add_submission_number(self):
# self.submission_number = models.F("submission_number") + 1
# self.save()
# # 计算总分时, 应先减掉上次该题所得分数, 然后再加上本次所得分数
# def add_score(self, this_time_score, last_time_score=None):
# last_time_score = last_time_score or 0
# self.total_score = models.F("total_score") - last_time_score + this_time_score
# self.save()
# class Meta:
# db_table = "user_profile"

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

@ -0,0 +1,7 @@
from django.urls import path
from . import views
urlpatterns = [
path('login',views.login , name='login'),
]

@ -0,0 +1,22 @@
from django.shortcuts import render
from django.http import HttpResponse
from .models import User
# Create your views here.
def login(request):
if request.method == 'POST':
# 从前端数据中拿去表中字段
user_name = request.POST.get('user_name')
user_password = request.POST.get('user_password')
user_password_confirm = request.POST.get('user_password_confirm')
# 根据用户名查询数据库,并获得用户
user_obj = User.objects.filter(user_name=user_name).first()
if user_obj.user_name == user_name and user_obj.user_password == user_password and user_obj.user_password_confirm == user_password_confirm:
return HttpResponse("登录成功")
else:
return HttpResponse("登录失败")
else:
return HttpResponse("登录失败")

@ -0,0 +1,16 @@
"""
ASGI config for xxm_oj 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/4.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'xxm_oj.settings')
application = get_asgi_application()

@ -0,0 +1,144 @@
"""
Django settings for xxm_oj project.
Generated by 'django-admin startproject' using Django 4.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.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/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-ifdstw@yn7m-tq%7n^=v&ivdo&hq-jxhi2djr=dcr$@-(n!zf&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'user.apps.UserConfig',
]
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 = 'xxm_oj.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 = 'xxm_oj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
# }
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'xxm_oj',
'USER':'root',
'PASSWORD':'root',
'HOST':'127.0.0.1',
'PORT':'3306',
'DEFAULT-CHARACTER-SET':'utf8',
}
}
# my.cnf [client]
# database = NAME
# user = USER
# password = PASSWORD
# default-character-set = utf8
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
# USE_TZ = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# AVATAR_URI_PREFIX = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

@ -0,0 +1,22 @@
"""xxm_oj URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.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 path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('user/',include('user.urls')),
]

@ -0,0 +1,16 @@
"""
WSGI config for xxm_oj 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/4.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'xxm_oj.settings')
application = get_wsgi_application()
Loading…
Cancel
Save