Explorar o código

新建了account应用,用于存储用户相关信息,已完成form,model,完成了view的login部分,建立了template结构,接下来开始register以及profile修改的操作

Shellmiao %!s(int64=4) %!d(string=hai) anos
pai
achega
c5691fb8d2

+ 9 - 9
MeChat/settings.py

@@ -15,7 +15,6 @@ import os
 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
-
 # Quick-start development settings - unsuitable for production
 # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
 
@@ -27,7 +26,6 @@ DEBUG = True
 
 ALLOWED_HOSTS = []
 
-
 # Application definition
 
 INSTALLED_APPS = [
@@ -37,6 +35,8 @@ INSTALLED_APPS = [
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
+    'chat',
+    'account',
 ]
 
 MIDDLEWARE = [
@@ -54,7 +54,7 @@ ROOT_URLCONF = 'MeChat.urls'
 TEMPLATES = [
     {
         'BACKEND': 'django.template.backends.django.DjangoTemplates',
-        'DIRS': [],
+        'DIRS': [os.path.join(BASE_DIR, 'templates')],
         'APP_DIRS': True,
         'OPTIONS': {
             'context_processors': [
@@ -69,7 +69,6 @@ TEMPLATES = [
 
 WSGI_APPLICATION = 'MeChat.wsgi.application'
 
-
 # Database
 # https://docs.djangoproject.com/en/2.0/ref/settings/#databases
 
@@ -80,7 +79,6 @@ DATABASES = {
     }
 }
 
-
 # Password validation
 # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
 
@@ -99,13 +97,12 @@ AUTH_PASSWORD_VALIDATORS = [
     },
 ]
 
-
 # Internationalization
 # https://docs.djangoproject.com/en/2.0/topics/i18n/
 
-LANGUAGE_CODE = 'en-us'
+LANGUAGE_CODE = 'zh-hans'
 
-TIME_ZONE = 'UTC'
+TIME_ZONE = 'Asia/Shanghai'
 
 USE_I18N = True
 
@@ -113,8 +110,11 @@ USE_L10N = True
 
 USE_TZ = True
 
-
 # Static files (CSS, JavaScript, Images)
 # https://docs.djangoproject.com/en/2.0/howto/static-files/
 
 STATIC_URL = '/static/'
+
+STATICFILES_DIRS = (
+    os.path.join(BASE_DIR, "static"),
+)

+ 3 - 1
MeChat/urls.py

@@ -14,8 +14,10 @@ Including another URLconf
     2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
 """
 from django.contrib import admin
-from django.urls import path
+from django.urls import path, include
 
 urlpatterns = [
     path('admin/', admin.site.urls),
+    path('chat/', include('chat.urls')),
+    path('account/', include('account.urls')),
 ]

+ 5 - 1
README.md

@@ -1,2 +1,6 @@
 # MeChat
-端对端加密通讯工具的初级版本demo,为接下来的开发(对通讯中的信息进行加密)提供明文传输版本
+端对端加密通讯工具的初级版本demo,为接下来的开发(对通讯中的信息进行加密)提供明文传输版本
+## 使用
+### settings.py的编辑
+将LANGUAGE_CODE修改为你的语言
+将TIME_ZONE修改为你的时区

+ 0 - 0
account/__init__.py


+ 3 - 0
account/admin.py

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

+ 6 - 0
account/apps.py

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

+ 30 - 0
account/form.py

@@ -0,0 +1,30 @@
+from django import forms
+from django.contrib.auth.models import User
+from .models import Profile
+
+
+class UserLoginForm(forms.Form):
+    username = forms.CharField()
+    password = forms.CharField()
+
+
+class UserRegisterForm(forms.ModelForm):
+    password = forms.CharField()
+    password2 = forms.CharField()
+
+    class Meta:
+        model = User
+        fields = ('username', 'email')
+
+    def clean_password2(self):
+        data = self.cleaned_data
+        if data.get('password') == data.get('password'):
+            return data.get('password')
+        else:
+            return forms.ValidationError('密码输入不一致,请重新输入!')
+
+
+class ProfileForm(forms.ModelForm):
+    class Meta:
+        model = Profile
+        fields = ('phone', 'bio')

+ 26 - 0
account/migrations/0001_initial.py

@@ -0,0 +1,26 @@
+# Generated by Django 3.2.5 on 2021-07-06 06:51
+
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+    initial = True
+
+    dependencies = [
+        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='Profile',
+            fields=[
+                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('phone', models.CharField(blank=True, max_length=20)),
+                ('bio', models.TextField(blank=True, max_length=500)),
+                ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)),
+            ],
+        ),
+    ]

+ 0 - 0
account/migrations/__init__.py


+ 32 - 0
account/models.py

@@ -0,0 +1,32 @@
+from django.db import models
+from django.contrib.auth.models import User
+# 引入内置信号
+from django.db.models.signals import post_save
+# 引入信号接收器的装饰器
+from django.dispatch import receiver
+
+
+# 用户信息
+class Profile(models.Model):
+    # 对应django自带的user
+    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
+    # 电话
+    phone = models.CharField(max_length=20, blank=True)
+    # 个人简介
+    bio = models.TextField(max_length=500, blank=True)
+
+    def __str__(self):
+        return 'user {}'.format(self.user.username)
+
+
+# 信号接收函数,每当新建User实例的时候自动调用
+@receiver(post_save, sender=User)
+def create_user_profile(sender, instance, created, **kwargs):
+    if created:
+        Profile.objects.create(user=instance)
+
+
+# 信号接收函数,每当更新User实例的时候自动调用
+@receiver(post_save, sender=User)
+def save_user_profile(sender, instance, **kwargs):
+    instance.profile.save()

+ 20 - 0
account/templates/login.html

@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<html lang="zh-cn">
+    <div>
+        <form method="post" action=".">
+            {% csrf_token %}
+            <!-- 账号 -->
+            <div>
+                <label for="username">账号</label>
+                <input type="text" id="username" name="username">
+            </div>
+            <!-- 密码 -->
+            <div>
+                <label for="password">密码</label>
+                <input type="text" id="password" name="password">
+            </div>
+            <!-- 提交按钮 -->
+            <button type="submit">提交</button>
+        </form>
+    </div>
+</html>

+ 3 - 0
account/tests.py

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

+ 6 - 0
account/urls.py

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

+ 28 - 0
account/views.py

@@ -0,0 +1,28 @@
+from django.shortcuts import render, redirect
+from .form import UserLoginForm, UserRegisterForm
+from django.contrib.auth import authenticate, login
+from django.http import HttpResponse
+
+
+def user_login(request):
+    if request.method == 'POST':
+        user_login_form = UserLoginForm(request.POST)
+        if user_login_form.is_valid():
+            # 清洗出合法的数据
+            data = user_login_form.cleaned_data
+            # 检测账号密码是否匹配数据库中的一个用户
+            # 如果均匹配,则返回此User对象
+            user = authenticate(username=data['username'], password=data['password'])
+            if user:
+                login(request, user)
+                return redirect("chat:index")
+            else:
+                return HttpResponse("账号或密码输入不正确,请重新输入")
+        else:
+            return HttpResponse("输入不合法,请重新输入")
+    elif request.method == 'GET':
+        user_login_form = UserLoginForm()
+        context = {'form': user_login_form}
+        return render(request, 'login.html', context)
+    else:
+        return HttpResponse("请使用GET或者POST请求数据")

BIN=BIN
db.sqlite3