Python realizes the user registration and mailbox verification function code through Django
- 2020-06-15 09:36:17
- OfStack
This paper mainly shares the Python programming through Django module to achieve user registration and mailbox verification function of the simple introduction and code implementation, specific as follows.
User Registration:
Similar to user login, also add RegisterView(View) class to users.views.py, which handles get and post for forms.
If it is the get method, go back to the register page and let the user fill it out.
def get(self, request):
register_form = RegisterForm()
return render(request, "register.html", {'register_form':register_form})
When method = POST, user registration logic:
def post(self, request):
# instantiation form To verify that each field is valid
register_form = RegisterForm(request.POST)
pre_check = register_form.is_valid()
if pre_check:
# Take out the email and password
user_name = request.POST.get("email", "")
pass_word = request.POST.get("password", "")
# Instantiate the user, and then assign a value
user_profile = UserProfile()
user_profile.username = user_name
user_profile.email = user_name
# A new user is an inactive user and can be authenticated as an active user
user_profile.is_active = False
# Converts plaintext to ciphertext assignment password
user_profile.password = make_password(pass_word)
user_profile.save() # Save to database
# A means of mailbox verification has been added here
send_register_email(user_name, "register")
return render(request, "login.html")
else:
# form The form validation fails, sending an error message to the front end
return render(request, "register.html", {"register_form": register_form})
Add the RegisterForm class pair to form.py to give the form processing class:
class RegisterForm(forms.Form):
# Can't be empty
email = forms.EmailField(required=True)
password = forms.CharField(required=True, min_length=6 . max_length=20)
# An error message
captcha = CaptchaField(error_messages={"invalid":u" Verification code error "})
The following is the corresponding front-end code, in which django template usage is added, logic is added in html in the form of {% %}, avoiding the direct insertion of python code, which is convenient for maintenance and modification.
<form id="email_register_form" method="post" action="{% url 'register' %}" autocomplete="off">
<div class="form-group marb20 {% if register_form.errors.email %}errorput{% endif %}">
<label> mail box </label>
<input type="text" id="id_email" name="email" value="{{ register_form.email.value }}" placeholder=" Please enter your email address " />
</div>
<div class="form-group marb8 {% if register_form.errors.password %}errorput{% endif %}">
<label> The secret code </label>
<input type="password" id="id_password" name="password" value="{{ register_form.password.value }}" placeholder=" Please enter the 6-20 Bit non - Chinese character password " />
</div>
<div class="form-group marb8 captcha1 {% if register_form.errors.captcha %}errorput{% endif %}">
<label> check the code </label>
{{ register_form.captcha }}
</div>
<div class="error btns" id="jsEmailTips">{% for key,error in register_form.errors.items %}{{ error }}{% endfor %} {{ msg }}</div>
<div class="auto-box marb8">
</div>
<input class="btn btn-green" id="jsEmailRegBtn" type="submit" value=" Register and log in " />
{% csrf_token %}
</form>
{% csrf_token %} is django's protection against cross-site attack when a user submits a form. If the form is not added at the end, it cannot be submitted normally
One item in the form is captcha, which can be implemented in django using django-ES43en-ES44en module:
url(r'^captcha/', include(' captcha.urls ')) configuration url
{{es55EN_form.captcha}} configure the front end
Email verification:
model with mailbox verification added in ES63en.ES64en:
class EmailVerifyRecord(models.Model):
# Verification code
code = models.CharField(max_length=20, verbose_name=u" Verification code ")
email = models.EmailField(max_length=50, verbose_name=u" email ")
# Includes registration validation and retrieve validation
send_type = models.CharField(verbose_name=u" Captcha type ", max_length=10, choices=(("register",u" registered "), ("forget",u" Retrieve password ")))
send_time = models.DateTimeField(verbose_name=u" Send time ", default=datetime.now)
class Meta:
verbose_name = u" Email verification code "
verbose_name_plural = verbose_name
def __unicode__(self):
return '{0}({1})'.format(self.code, self.email)
Add configuration mailbox information in ES69en.py:
EMAIL_HOST = "smtp.163.com" # The server
EMAIL_PORT = 25 # 1 Generally speaking 25
EMAIL_HOST_USER = "abc@163.com" # account
EMAIL_HOST_PASSWORD = "password" # password
EMAIL_USE_TLS = False # 1 As for the False
EMAIL_FROM = "abc@163.com" # Email from
Create utils package and create new ES75en_send.py
from random import Random # Used to generate random codes
from django.core.mail import send_mail # Send mail module
from users.models import EmailVerifyRecord # Email address verification model
from MxOnline.settings import EMAIL_FROM # setting.py Added configuration information
# Generate random strings
def random_str(randomlength=8):
str = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length = len(chars) - 1
random = Random()
for i in range(randomlength):
str+=chars[random.randint(0, length)]
return str
def send_register_email(email, send_type="register"):
email_record = EmailVerifyRecord()
# Save the information sent to the user in the database
code = random_str(16)
email_record.code = code
email_record.email = email
email_record.send_type = send_type
email_record.save()
# Initialize null
email_title = ""
email_body = ""
# If it is a registration type
if send_type == "register":
email_title = " Sign up for activation link "
email_body = " Please click the link below to activate your account :http://127.0.0.1:8000/active/{0}".format(code)
# Send E-mail
send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
if send_status:
pass
Then turn the user into an active user and add the relevant view:
class ActiveUserView(View):
def get(self, request, active_code):
# with code Filter information in the database
all_records = EmailVerifyRecord.objects.filter(code=active_code)
if all_records:
for record in all_records:
email = record.email
# Find the corresponding user through the mailbox
user = UserProfile.objects.get(email=email)
# To activate the user
user.is_active = True
user.save()
else:
return render(request, "active_fail.html")
return render(request, "login.html")
Configure url for the generated page:
url(r'^active/(?P<active_code>.*)/$', ActiveUserView.as_view(), name="user_active"), # Extract the active Any subsequent characters assigned to active_code
At this point, you can add is_active to the login restrictions:
if user.is_active:
login(request, user) # call login Method Login account
return render(request, "index.html")
else:
return render(request, "login.html", {"msg": u" User inactive "})
conclusion
Above is this article on Python through Django to achieve user registration and email verification function code all content, I hope to help you. Those who are interested can continue to see other related topics on this site. If there is any deficiency, please let me know. Thank you for your support!