SoFunction
Updated on 2024-11-19

Django mall project registration function implementation

Designed to front-end knowledge

The front-end page of the project uses vue to achieve local refresh, through the two-way binding of data to achieve the interaction with the user, the following look at the requirements, after the user input content, the front-end needs to do some simple rule checking, we want to be able to detect the real-time detection of the user input, if there is an error to be able to show up in the bottom of the input box.

<li>
    <label>user ID:</label>
    <input type="text" name="username" >
    <span class="error_tip">Please enter5-20user of one character</span>
</li>
<li>
    <label>cryptographic:</label>
    <input type="password" name="password" >
    <span class="error_tip">Please enter8-20位的cryptographic</span>
</li>

Above is a user and password input box, when the user enters the user name, the cursor leaves the input box, to detect the correctness of the input content in real time, when there is a problem with the input, the error message is displayed at the bottom of the input box.

v-model to realize the two-way binding of data, v-on for event binding, v-show is to control the dom display or not, the following is part of the code after adding vue

<li>
    <label>user ID:</label>
    <input type="text" name="username"  v-model="username" @blur="check_username">
    <span class="error_tip" v-show="error_name">[[error_name_message]]</span>
</li>
<li>
    <label>cryptographic:</label>
    <input type="password" name="password"  v-model="password" @blur="check_password">
    <span class="error_tip" v-show="error_password">Please enter8-20位的cryptographic</span>
</li>

The user input username and username variable binding, the cursor disappears to trigger the binding time check_username, through the v-show binding to the boolean variable error_name, to control whether to display the string variable error_name_message, the other input boxes are similar to this operation.

Registered Business Realization

Front-end registration business logic

Registration form code:

<form method="post" class="register_form" >
    {{ csrf_input }}
    <ul>
        <li>
            <label>user ID:</label>
            <input type="text" name="username"  v-model="username" @blur="check_username">
            <span class="error_tip" v-show="error_name">[[error_name_message]]</span>
        </li>
        <li>
            <label>cryptographic:</label>
            <input type="password" name="password"  v-model="password" @blur="check_password">
            <span class="error_tip" v-show="error_password">Please enter8-20位的cryptographic</span>
        </li>
        <li>
            <label>确认cryptographic:</label>
            <input type="password" v-model="password2" @blur="check_password2" name="password2"
                   >
            <span class="error_tip" v-show="error_password2">两次输入的cryptographic不一致</span>
        </li>
        <li>
            <label>cell phone number:</label>
            <input type="text" v-model="mobile" @blur="check_mobile" name="mobile" >
            <span class="error_tip" v-show="error_mobile">[[ error_mobile_message ]]</span>
        </li>

        <li>
            <label>CAPTCHA:</label>
            <input type="text" name="image_code"  class="msg_input">
            <img src="{{ static('images/pic_code.jpg') }}" alt="Graphical CAPTCHA" class="pic_code">
            <span class="error_tip">请填写CAPTCHA</span>
        </li>
        <li>
            <label>CAPTCHA:</label>
            <input type="text" name="sms_code"  class="msg_input">
            <a href="javascript:;" rel="external nofollow"  class="get_msg_code">获取CAPTCHA</a>
            <span class="error_tip">请填写CAPTCHA</span>
        </li>
        <li class="agreement">
            <input type="checkbox" name="allow"  v-model="allow" @change="check_allow">
            <label>agree with”Mall User Agreement“</label>
            <span class="error_tip" v-show="error_allow">Please check the user agreement</span>
        </li>
        <li class="reg_sub">
            <input type="submit" value="Registered" @change="on_submit">
            {% if register_errmsg %}
                <span class="error_tip2">{{ register_errmsg }}</span>
            {% endif %}
        </li>
    </ul>
</form>

Import and ajax request js library

<script type="text/javascript" src="{{ static('js/vue-2.5.') }}"></script>
<script type="text/javascript" src="{{ static('js/axios-0.18.') }}"></script>

Prepare the document

The file mainly handles the interaction events of the registration page and submits the registration form request to the server.

<script type="text/javascript" src="{{ static('js/') }}"></script>

The following is the front-end validation logic and form submission logic implemented

methods: {
    // Verify the username
    check_username() {
        let re = /^[a-zA-Z0-9_-]{5,20}$/;
        if (()) {
            this.error_name = false;
        } else {
            this.error_name_message = 'Please enter a username of 5-20 characters';
            this.error_name = true;
        }
    },
    // Verify the password
    check_password() {
        let re = /^[0-9A-Za-z]{8,20}$/;
        this.error_password = !();
    },
    // Verify confirmation password
    check_password2() {
        if ( !== this.password2) {
            this.error_password2 = true;
        } else {
            this.error_password2 = false;
        }
    },
    // Verify cell phone number
    check_mobile() {
        let re = /^1[3-9]\d{9}$/;
        if (()) {
            this.error_mobile = false;
        } else {
            this.error_mobile_message = 'The cell phone number you entered is not in the correct format';
            this.error_mobile = true;
        }
    },
    // Verify that the protocol is checked
    check_allow() {
        this.error_allow = !;
    },
    // Listen for form submission events
    on_submit() {
        this.check_username();
        this.check_password();
        this.check_password2();
        this.check_mobile();
        this.check_allow();
				# Disable if one of the input fields doesn't match the rule
        if (this.error_name === true || this.error_password === true || this.error_password2 === true
            || this.error_mobile === true || this.error_allow === true) {
            // Disable form submission
             = false;
        }
    },
}

Backend Business Registration Logic

In the user to lose the user name, we often want to be able to follow the fastest to give the user name is in line with the registration requirements, in front of the user name is just the rules of the verification, but also want to know whether he has been registered in the system, or when the user is lost to submit the registration and then give the user name or cell phone number has been registered, the experience is not particularly good. So you need to leave the cursor in the user name input box when you request the server to determine whether the registration.

Defining Routes

path('register/', .as_view(), name='register'),  # name add namespace
path('usernames/<str:username>', .as_view(), name="username"),
re_path(r'mobiles/(?P<mobile>1[3-9]\d{9})', .as_view(), name='mobile')

Writing view classes

class UsernameCountView(View):

    def get(self, request, username):
        """
        Queries if the username exists in the system
        :param request: the request object
        :param username: the username passed to the frontend
        :return.
        """
        count = (username=username).count()
        return ({'code':1001, 'msg':'User already exists'}) if count == 1 \
            else ({'code': 1000, 'msg': ''})

There is no unified treatment encapsulation of the response here, which is specifically described later.

Then it's time to write the registered view class:

class RegisterView(View):
    """User Registration View Class"""

    def get(self, request):
        '''Get Registration Page'''
        return render(request, '')

    def post(self, request):
        """"""
        username = ('username')
        password = ('password')
        password2 = ('password2')
        mobile = ('mobile')
        allow = ('allow')
        # Determine if the parameters are complete
        if not all([username, password, password2, mobile, allow]):
            return ('Missing mandatory parameter')
        # Determine if the username is 5-20 characters
        if not (r'^[a-zA-Z0-9_-]{5,20}$', username):
            return ('Please enter a username of 5-20 characters')
        # Determine if the password is 8-20 numbers
        if not (r'^[0-9A-Za-z]{8,20}$', password):
            return ('Please enter a password of 8-20 digits')
        # Determine if two passwords are the same
        if password != password2:
            return ('Inconsistent password entered twice')
        # Determine if a cell phone number is legitimate
        if not (r'^1[3-9]\d{9}$', mobile):
            return ('Please enter the correct cell phone number')
        # Determine whether the user agreement is checked or unchecked
        if allow != 'on':
            return ('Please check the user agreement')

        try:
            user = .create_user(username=username, password=password, mobile=mobile)
        except DatabaseError as e:
            return render(request, '', {'register_errmsg': })

        # Registration Successfully Saved Sessions
        login(request, user)

        return redirect(reverse('contents:index'))

The login method provided by django encapsulates the operation of writing to a session, which helps us to quickly log in a user and achieve stateful retention by writing the authenticated user's unique identifier information (e.g., user ID) to the current browser's cookie and the server-side session.

[SESSION_KEY] = user._meta.pk.value_to_string(user)
[BACKEND_SESSION_KEY] = backend
[HASH_SESSION_KEY] = session_auth_hash

The session will be stored in redis, previously configured for session storage during project creation

SESSION_ENGINE = ""
SESSION_CACHE_ALIAS = "session"

Link./s/1dFliI6KkNubd4k_OTEpqDA Extract code: h3dp

Above is the realization of Django mall project registration function of the details , more about Django registration function of the information please pay attention to my other related articles !