Django实现注册页面_头像上传

Django实现注册页面_头像上传

Django实现注册页面_头像上传

1.urls.py 配置路由

from django.conf.urls import url
from django.contrib import admin
from blog import views

from django.views.static import serve
from meblog import settings

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', views.login),
    #
    url(r'^get_valid_img/', views.get_valid_img),
    url(r'^index/', views.index),
    url(r'^reg/', views.reg),

    # media 配置 图片存储路径可直接访问
    url(r'^media/(?P.*)$', serve, {"document_root": settings.MEDIA_ROOT}),
]

2.在app 包路径 创建一个forms.py 用于定义类:

from django import forms

from django.forms import widgets
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError


class RegForm(forms.Form):
    username = forms.CharField(min_length=5,
                               # 定义 class 类型 form-control 为 bootcss 样式
                               widget=widgets.TextInput(attrs={"class": "form-control"})
                               )
    password = forms.CharField(min_length=5,
                               widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    repeat_password = forms.CharField(min_length=5,
                                      widget=widgets.PasswordInput(attrs={"class": "form-control"})
                                      )
    email = forms.EmailField(min_length=5,
                             widget=widgets.TextInput(attrs={"class": "form-control"})
                             )

    # 清洗全局 钩子用于清洗 两次用户输入的密码是否一致
    def clean(self):
        if self.cleaned_data.get("password") == self.cleaned_data.get("repeat_password"):
            return self.cleaned_data
        else:
            raise ValidationError("两次密码不一致")

3.视图views.py页面配置

from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
from PIL import Image
from django.contrib import auth
from .models import *
import json
from django.contrib.auth.decorators import login_required
from blog.forms import RegForm

def reg(request):
    if request.is_ajax():
        regForm = RegForm(request.POST)
        regResponse = {"user": None, "error_msg": None}
        if regForm.is_valid():                                    # is_valid() 是已经验证过的数据
            username = regForm.cleaned_data.get("username")
            password = regForm.cleaned_data.get("password")
            email = regForm.cleaned_data.get("email")
            avatar = request.FILES.get("imgFile")                 # 获取模板传入的 图片

            user = UserInfo.objects.create_user(username=username, password=password, email=email, avatar=avatar)
            regResponse["user"] = user.username
        else:
            regResponse["error_msg"] = regForm.errors

        return HttpResponse(json.dumps(regResponse))
    regForm = RegForm()
    return render(request, "reg.html", {"regForm": regForm})

4.模板页面reg.html




    
    

    
    
    
    
    



{ { regForm.username }}
{ { regForm.password }}
{ { regForm.repeat_password }}
{ { regForm.email }}

5.定义models.py表里设置头像文件的存放位置

from django.db import models
# Create your models here.
from django.contrib.auth.models import AbstractUser

class UserInfo(AbstractUser):
    """
    用户信息
    """

    nid = models.AutoField(primary_key=True)
    nickname = models.CharField(verbose_name='昵称', max_length=32)
    telephone = models.CharField(max_length=11, blank=True, null=True, unique=True, verbose_name='手机号码')
    
    # 用户上传的数据会根据该目录,结合UserInfo表中upload_to='avatarDir/' 参数来拼接当前目录
    avatar = models.FileField(verbose_name='头像', upload_to='avatarDir/', default="avatar/default.png")
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    blog = models.OneToOneField(to='Blog', to_field='nid', null=True)

    def __str__(self):
        return self.username

6.settings.py 配置 MEDIA_ROOT 路径;用于存放用户上传得文件

MEDIA_ROOT = os.path.join(BASE_DIR, "blog", "media")

MEDIA_URL = "/media/"

转载于:https://www.cnblogs.com/baolin2200/p/8033836.html

你可能感兴趣的:(python,json,javascript)