I. Introduction In the first few articles of this series, bloggers have shared the function of how to build a web user login registration system and real-time video sharing under the Django framework. Today, we integrate it and add pages to form a set of web users. Interactive system.
2. Code analysis Code architecture
Figure 1 code architecture
2. Main code sharing
Online/view.py
#coding=utf-8
From django.shortcuts import render,render_to_response
From django.http import HttpResponse, HttpResponseRedirect
From django.template import RequestContext
From django import forms
From online.models import MyUser
From online.models import Message
From online.models import SystemStatus
From django.contrib.auth import authenTIcate, login
From django.uTIls import TImezone
Import os
Import json
Import encodings
#form
Class UserForm(forms.Form):
Username = forms.CharField(label='username', max_length=100)
Password = forms.CharField(label='password', widget=forms.PasswordInput())
#def getuser(forms):
# return forms.username
# password1 = forms.CharField(label='repeat password', widget=forms.TexTInput())
# loginaddr="http://127.0.0.1:8000/online/login/"
# registaddr=http://127.0.0.1:8000/online/regist/
#registered
Def regist(req):
If req.method == 'POST':
Uf = UserForm(req.POST)
If uf.is_valid():
#Get form data
Username = uf.cleaned_data['username']
Password = uf.cleaned_data['password']
Password1 = req.POST['password1']
#Compare whether there are users in the database
#user = myUser.objects.all().filter(username = username)
#print(user)
If MyUser.objects.filter(username =username).exists():
Return render_to_response('registfaild.html',{'uf':uf}, context_instance=RequestContext(req))
Else:
If password1==password:
User=MyUser.objects.create(username= username,password=password)#Add users to the database
# profile=UserProfile()#e************************
# profile.user_id=user.id
# profile.phone=phone
# profile.save()
# user = MyUser.objects.create_user(username=username,password=password)
Print(user.is_staff) #True
#user.set_password(password)
User.save()
Print(user.id)
#user.userID=user.id
#user.save()
#print(user.userID)
#user_sum=MyUser.objects.all().values('username').count()
#user.userID=user_sum
#print(user.userID)
#user.save()
Response = HttpResponseRedirect('/online/registsuccee/')
Return response
Else:
Return render_to_response('registfaild1.html',{'uf':uf}, context_instance=RequestContext(req))
Else:
Uf = UserForm()
Return render_to_response('regist.html',{'uf':uf}, context_instance=RequestContext(req))
Def createSystemstatus():#Create system status information
#SystemStatus.objects.filter().delete()
SystemRecord=SystemStatus.objects.filter().count()# returns all status information objects
Print('SystemRecord = ',SystemRecord)
If SystemRecord == 0:#System status information is only created one, if it has been created, it is no longer created
Print('create systemstatus')
Systemstatus=SystemStatus()
systemstatus.statusName="peopleInfront"
systemstatus.statusValue=-1
Systemstatus.statusParam=0
systemstatus.statusDiscirption="no people in front"
Systemstatus.save()
Print('statusName = ',systemstatus.statusName)
Print('statusDiscirption = ',systemstatus.statusDiscirption)
Else:
Print(' systemstatus had credted')
#ç™»
Def loginin(req):
# getAllUser(req)
createSystemstatus()#Create a server-wide unique system state object
User_firstflag=True #Initialize the receive user selection flag
Print(timezone.localtime(timezone.now()).strftime("%Y-%m-%d %H:%M:%S"))
#Get the local IP
#myname = socket.getfqdn(socket.gethostname( ))
#å–本ip ip
#myaddr = socket.gethostbyname(myname)
#print('myname is ',myname,'myaddr = ',myaddr)
If req.method == 'POST':
Uf = UserForm(req.POST)
If uf.is_valid():
#Get form user password
Username = uf.cleaned_data['username']
Password = uf.cleaned_data['password']
#Get the form data compared with the database
User = MyUser.objects.filter(username__exact = username,password__exact = password)
#user = authenticate(username=username, password=password)
If user:
#比较æˆåŠŸ, jump index
Response = HttpResponseRedirect('/online/index/')
#good="xiaoms"
#Write username to browser cookie, invalidation time is 3600
Response.set_cookie('username',username,3600)
Response.set_cookie('user_firstflag',user_firstflag,3600)# After successful login, the first user is not selected recipient
Return response
Else:
# Compare failure, jump loginfaild
Return render_to_response('loginfaild.html',{'uf':uf},context_instance=RequestContext(req))
Else:
Uf = UserForm()
Return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))
#def loginfaild(req):
# response = login(req)
# return response
#
Def registsuccee(req):
If req.method == 'POST':
Uf = UserForm(req.POST)
If uf.is_valid():
#Get form user password
Username = uf.cleaned_data['username']
Password = uf.cleaned_data['password']
#Get the form data compared with the database
User = MyUser.objects.filter(username__exact = username,password__exact = password)
If user:
#比较æˆåŠŸ, jump index
Response = HttpResponseRedirect('/online/index/')
#Write username to browser cookie, invalidation time is 3600
Response.set_cookie('username',username,3600)
Return response
Else:
# Compare failure, jump loginfaild
Return render_to_response('loginfaild.html',{'uf':uf},context_instance=RequestContext(req))
Else:
Uf = UserForm()
#return render_to_response('registfaild.html',{'uf':uf},context_instance=RequestContext(req))
Return render_to_response('registsuccee.html',{'uf':uf},context_instance=RequestContext(req))
#
#def registfaild(req):
# response = regist(req)
# return response
#
#def registfaild1(req):
# response = regist(req)
# return response
Def jsonclient(req):#Get the json object
Try:
Print("start json POST")
Req = json.loads((req.body).decode())
Print("get json succee")
Return req
Except:
Import sys
Info = "%s || %s" % (sys.exc_info()[0], sys.exc_info()[1])
Print(info)
Def datasave(request): #解æ¿json object and save
Info = 'Data log save success'
Try:
If request.method == 'POST':
Print("start json POST")
Req = json.loads((request.body).decode())
User = req['user']
infoType = req['infoType']
Name = req['name']
Print(name)
Print(infoType)
Print(user)
Except:
Import sys
Info = "%s || %s" % (sys.exc_info()[0], sys.exc_info()[1])
Print(info)
Dict['message']=info
Return HttpResponse(json)
Def getOtherUser(req,name):
Userlogin=MyUser.objects.filter(username__exact=name)#Retrieve the currently logged in user
Print(userlogin)
Print(userlogin.id)
User_list=MyUser.objects.all().values('username','id').exclude(id__in=userlogin.id)
# user_sum=MyUser.objects.all().values('username').count()
Print(user_list)
# print(user_sum)
Return user_list
Def getAllUser(req):#Get all registered users
User_list=MyUser.objects.all().values('username','id').order_by('id')
User_sum=MyUser.objects.all().values('username').count()
Print(user_list)
Print(user_sum)
Return user_list
#Landed successfully
Def index(req):
Username = req.COOKIES.get('username','')
User_list=getAllUser(req)# retrieves all user objects with username and id
i=0
For list in user_list:
Name=list.get('username').encode()
User_list[i].update({'username':name})
i=i+1
Print('user_list == ',user_list)
#good=req.COOKIES.get('good','')
#print('good = ',good)
#user_list=getOtherUser(req,username)#Retrieve all users except the currently logged in user
#user_first=user_list[0].username
User_first=username #temporarily use the logged in person as the default recipient
#user_sum=MyUser.objects.all().values('username').count()#Number of registered users
#print(user_sum)
#datasave(req)
Key_input=0
If req.method == 'POST':
Print('index.username first= ',username)
Json=jsonclient(req)#Get the json object
If json is not None: #judge whether to select the user or select the input method
User_ower = json['ownerID']#Get owerID
Print('json is not none user_ower = ',user_ower)
#message=Message()#Create a message object when selecting a message recipient
Response = render_to_response('login_user.html' ,{'user_list':user_list,'username':username,'user_first':user_first},context_instance=RequestContext(req))
Response.set_cookie('ownerID',user_ower,3600)
Return response
Else:
ownerID = req.COOKIES.get('ownerID','')#Get the recipient ID
Print('the message ownerID is',ownerID)
If ownerID:# If there is a choice, use the selector
User_ower=ownerID
Else:# otherwise the default is pushed to the sender itself
Uower=MyUser.objects.get(username__exact=username)
User_ower=Uower.id
# message=Message.objects.get(id=messid)
#user_ower=message.ownerID
Message=Message()#Create a message. Note that even if the message recipient is not selected for the first time, the default message object should be created. The default receiving ID is the sender itself.
infoType_c=req.POST['submit']#How to get information
infoType=int(infoType_c)
Print('index:infotType=',infoType)
Key_user=user_ower
Key_input=infoType
Print('key_user=',key_user)
Print('key_input=',key_input)
User_push=MyUser.objects.get(username__exact=username)
Print('username=',username)
Print('user_push=',user_push)
message.infoType=infoType# type of push message
message.pushID=user_push.id#pender ID
message.ownerID= key_user#recipient's ID
message.pushTim=timezone.localtime(timezone.now()).strftime("%Y-%m-%d %H:%M:%S")
message.isTop = 0 #top flag default 1
message.viewWeight = 1# reading level default 1
Message.save()
Print('message.id=',message.id)
Messid=message.id
Print('messid=',messid)
# Due to the post bug, here is the html5 front end to save our messy
If key_input == 0:
Print('please input text')
Response = HttpResponseRedirect('/online/text/')
#Write username to browser cookie, invalidation time is 3600
Response.set_cookie('username',username,3600)
Response.set_cookie('messid',messid,3600)
Print('index:messid=',messid)
Return response
Elif key_input == 1:
Print('please input video')
Response = HttpResponseRedirect('/online/video/')
#Write username to browser cookie, invalidation time is 3600
Response.set_cookie('username',username,3600)
Response.set_cookie('messid',messid,3600)
Return response
Else:
Response = render_to_response('login_user.html' ,{'user_list':user_list,'username':username,'user_first':user_first,'messid':messid},context_instance=RequestContext(req))
Print('error ~! just donot in this page')
Response.set_cookie('messid',messid,3600)
Return response
#return render_to_response('loginsuccee.html' ,{'user_list':json.dumps(user_list),'username':username,'user_first':user_first,'messid':messid},context_instance=RequestContext(req))
Else:
Return render_to_response('login_user.html' ,{'user_list': user_list,'user_first':user_first,'username':username},context_instance=RequestContext(req))
#drop out
Def logout(req):
Response = HttpResponse('logout !!')
#Clean up the cookie to save the username
Response.delete_cookie('username')
Response.delete_cookie('messid')
Return response
#response = HttpResponse('logout !!')
#Clean up the cookie to save the username
# response.delete_cookie('username')
# return response
Def text(req):#Input text processing
Username = req.COOKIES.get('username','')
Messid= req.COOKIES.get('messid','')
Print('text:username=',username)
Print('text:messid=',messid)
If req.method == 'POST':
# json=jsonclient(req)#Get the json object
# messid1 = json['messid']#Get owerID
# print(messid1)
Text = req.POST['text_input']
#if text is not None:
User=MyUser.objects.get(username__exact=username)
Print('user.id=',user.id)
Print('messid=',messid)
#userID=user.id
Message=Message.objects.get(id=messid)
message.infoContent=text
Print(username)
Print('message.ownerID = ',message.ownerID)
Print('message.pushID =',message.pushID)
Print(message.infoContent)
#message.pushTim=timezone.localtime(timezone.now()).strftime("%Y-%m-%d %H:%M:%S")
Message.save()
Response = HttpResponseRedirect('/online/show/')
#Write username to browser cookie, invalidation time is 3600
Response.set_cookie('username',username,3600)
Return response
#els:
# return render_to_response('textfailed.html')
# print(dir(MyUser))
Return render_to_response('text1.html',context_instance=RequestContext(req))
Def video(req):#Input video processing
Username = req.COOKIES.get('username','')
Messid= req.COOKIES.get('messid','')
Print('video:username=',username)
Print('video:messid=',messid)
If req.method == 'POST':
f = req.FILES.get('video')
If f is not None:
baseDir = os.path.dirname(os.path.abspath(__name__))
Dir = os.path.join(baseDir,'static','save')
Filedir=os.path.join(dir,f.name)
Print('filedir = ',filedir)
Timename=timezone.localtime(timezone.now()).strftime("%Y%m%d%H%M%S")
#filename = os.path.join(dir,f.name)
Fname=os.path.splitext(f.name)
Fsuffix=fname[1]
Print('fsuffix =',fsuffix)
Filename = os.path.join(dir,timename+fsuffix)#Use local time number instead of any article name sent by the phone to avoid overlapping
Print('filename =',filename)
Fobj = open(filename,'wb')
For chrunk in f.chunks():
Fobj.write(chrunk)
Fobj.close()
Message=Message.objects.get(id=messid)
message.filePath=filename
Message.save()
Response = HttpResponseRedirect('/online/show/')
#Write username to browser cookie, invalidation time is 3600
Response.set_cookie('username',username,3600)
Return response
Else:
Return render_to_response('camera_reinput.html')
Else:
Return render_to_response('camera.html')
Def show(req):
Username = req.COOKIES.get('username','')
Messid = req.COOKIES.get('messid','')
Message=Message.objects.get(id=messid)
Print('message.infoContent',message.infoContent)
Return render_to_response('save.html',{'text':text,'username':username,'message.infoContent':message.infoContent})
Def delete():
MyUser.objects.filter().delete()
Online/models.py
#coding:utf8
From django.db import models
From django.contrib.auth.models import (
BaseUserManager , AbstractBaseUser , PermissionsMixin )
Class MyUserManager ( BaseUserManager ):
# def _create_user(self, username, email, password, **extra_fields):
Def _create_user ( self , username , password , ** extra_fields ):
"""
Creates and saves a User with the given username, email and password.
"""
If not username :
Raise ValueError ( 'The given username must be set' )
# email = self.normalize_email(email)
# user = self.model(username=username, email=email, **extra_fields)
User = self . model ( username = username , ** extra_fields )
User . set_password ( password )
User . save ( using = self . _db )
Return user
# def create_user(self, username, email, password, **extra_fields):
Def create_user ( self , username , password , ** extra_fields ):
Extra_fields . setdefault ( 'is_staff' , False )
Extra_fields . setdefault ( 'email' , "" )
Extra_fields . setdefault ( 'phone' , "" )
Extra_fields . setdefault ( 'haarValue' , "" )
Extra_fields . setdefault ( 'avatarImg' , "" )
# extra_fields.setdefault('text',"")
# extra_fields.setdefault('video',"")
# extra_fields.setdefault('time',"")
Return self . _create_user ( username , password , ** extra_fields )
# return self._create_user(username, email, password, **extra_fields)
# def create_superuser(self, username, email, password, **extra_fields):
Def create_superuser ( self , username , password , ** extra_fields ):
Extra_fields . setdefault ( 'is_staff' , True )
If extra_fields . get ( 'is_staff' ) is not True :
raise ValueError ( 'Superuser must have is_staff = True')
#拓展user data by xiao
#get
#to
#message_flag
#text
#video
#time
# extra_fields.setdefault('got',username)
# extra_fields.setdefault('to',username)
# extra_fields.setdefault('message_flag',"1")
# extra_fields.setdefault('text',"")
# extra_fields.setdefault('video',"")
# extra_fields.setdefault('time',"")
Return self . _create_user ( username , password , ** extra_fields )
# return self._create_user(username, email, password, **extra_fields)
Class MyUser ( AbstractBaseUser , PermissionsMixin ):
Username = models . CharField ( max_length = 254 , unique = True , db_index = True )
Email = models . CharField ( max_length = 254 )
Phone = models . CharField ( max_length = 254 )
haarValue = models . CharField ( max_length = 254 )
avatarImg = models . CharField ( max_length = 254 )
#email = models.EmailField('email address', max_length=254)
#text=models.CharField(max_length=254, unique=True, db_index=True)
Is_staff = models . BooleanField ( 'staff status' , default = False )
# userID = models.IntegerField(default=1) #User-specific ID
# is_active = models.BooleanField('active', default=True)
# got = models.CharField(max_length=254,default=username)
# to = models.CharField(max_length=254,default=username)
# message_flag = models.CharField(max_length=254, default=1)
# text = models.CharField(max_length=254, default="")
# video = models.CharField(max_length=254,default="")
# time = models.CharField(max_length=254,default="")
USERNAME_FIELD = 'username'
# REQUIRED_FIELDS = ['email']
Objects = MyUserManager ()
Class Meta :
Db_table = 'myuser'
# def get_full_name(self):
# return self.username
# def get_short_name(self):
# return self.username
#Build a model for pushing messages
Class Message ( models . Model ):
# username = models.CharField(max_length=254) #消æ¯æŽ¨è€…'s name
ownerID = models . IntegerField ( default = 1 )
pushID = models . IntegerField ( default = 1 )
infoType = models . IntegerField ( default = 0 )
infoSubject = models . CharField ( max_length = 254 )
infoContent = models . CharField ( max_length = 254 )
filePath = models . CharField ( max_length = 1000 )
pushTim = models . CharField ( max_length = 254 )
infoValidityTime = models . CharField ( max_length = 254 )
isTop = models . IntegerField ( default = 0 )
viewWeight = models . IntegerField ( default = 1 )
Def __unicode__ ( self ):
# Using def __str__(self) in Python 3
Return self . name
Class SystemStatus ( models . Model ): #Instance object: online_message MMDB.updateSystemStatus('peopleInfront',-1,0,'no people in front')
statusName = models . CharField ( max_length = 30 , default = "peopleInfront" )
statusValue = models . IntegerField ( default =- 1 )
statusParam = models . IntegerField ( default = 0 )
statusDiscirption = models . CharField ( max_length = 50 , default = "no people in front" )
Def __unicode__ ( self ):
# Using def __str__(self) in Python 3
Return self . name
Three. Demo renderings Figure 2 registration page
Figure 3 video upload page
Figure 4 message selection page
Figure 5 Upload success page
4. Routine sharing: Http://pan.baidu.com/share/link? Shareid=3536829173&uk=1812979481
Portable AC Ev Charger
China Portable 240V Ev Charger,Portable Electric Car Charger supplier & manufacturer, offer low price, high quality Portable Electric Vehicle Charger,Portable Level 2 Charger, etc.
Portable 240V Ev Charger,Portable Electric Car Charger,Portable Electric Vehicle Charger,Portable Level 2 Charger
Shenzhen Hongjiali New Energy Co., Ltd. , https://www.hjlcharger.com