检查AJAX中是否存在用户名

时间:2021-11-16 04:27:27

I've started to work with Django after a lot of PHP work. I got used to AJAX with PHP and it's working well. But I was doing procedural PHP so now in Django, I am a bit lost.

经过大量的PHP工作后,我开始使用Django。我习惯了使用PHP的AJAX,它运行良好。但我现在在Django做程序化PHP,我有点迷茫。

My first AJAX use case is very simple. I am doing a register page with a form and I would like to check in AJAX if the username the user filled in is available or not. I did it in Python, but now, I would like to do it in AJAX but I really don't know how to do it. Though the web, I found several tutorials but no one is the same as the others, and I don't know how to do it regarding my own code.

我的第一个AJAX用例非常简单。我正在使用表单进行注册页面,如果用户填写的用户名可用,我想检查AJAX。我是用Python做的,但现在,我想用AJAX做,但我真的不知道怎么做。虽然是网络,我找到了几个教程,但没有一个与其他教程相同,我不知道如何对我自己的代码这样做。

If you can guide me, that would be great.

如果你可以指导我,那就太好了。

views.py:

views.py:

from django.shortcuts import render
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
from membres.models import UserProfile, UserProfilePublic, UserProfilePrivate
from membres.forms import RegisterForm

def register(request):
    if request.method == 'POST':
        if request.is_ajax():
            if User.objects.filter(username=username).exists():
                return "exists"

        form = RegisterForm(request.POST)

        if form.is_valid():
            username = form.cleaned_data['username'].strip()
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            slug = slugify(username)

            user = User.objects.create_user(username, email, password)
            profile = UserProfile(user= user, slug= slug)
            profile.save()
            profile_public = UserProfilePublic(user= user)
            profile_public.save()
            profile_private = UserProfilePrivate(user= user)
            profile_private.save()

            form_validated = True

    else:
        form = RegisterForm()

    return render(request, 'membres/register.html', locals())

forms.py:

forms.py:

from django import forms
from django.contrib.auth.models import User

class RegisterForm(forms.Form):
    username = forms.CharField(min_length=5, max_length=30, required=True)
    email = forms.EmailField(max_length=75, required=True)
    password = forms.CharField(widget=forms.PasswordInput, required=True)
    password_check = forms.CharField(widget=forms.PasswordInput, required=True)

    def clean(self):
        cleaned_data = super(RegisterForm, self).clean()
        username = cleaned_data.get('username')
        email = cleaned_data.get('email')
        password = cleaned_data.get('password')
        password_check = cleaned_data.get('password_check')

        # Username
        if User.objects.filter(username=username).exists():
            msg = "Cet utilisateur existe déjà"
            self.add_error('username', msg)

        # Password
        if password_check != password:
            msg = "Le mot de passe et sa confirmation doivent être identiques"
            self.add_error('password_check', msg)

        return cleaned_data

register.html template:

register.html模板:

blur: function(){
        var value = $(this).val();
        var length = value.length;
        var id = $(this).attr('id');
        var label = $("label[for='"+id+"']");
        if($(this).parent().hasClass("field-mandatory")) {
            if(!value) {
                $("label[for='"+id+"']").append(checkStartInvalid + "Ne peut être vide" + checkEnd);
            } else {
                if(id == 'id_username') {
                    if(length < 5 || length > 30) {
                        label.append(checkStartInvalid + "Nombre de caractères compris entre 5 et 30" + checkEnd);
                    } else {
                        $.ajax({
                            url: '',
                            data: 'username='+value,
                            type: 'POST',
                            success: function(data){
                                console.log(data);
                            }
                        });
                        label.append(checkValid);
                    }
                }

As you can see in views.py I tried, but I get an error in the console: "NetworkError: 403 FORBIDDEN - ..."

正如您在views.py中看到的那样,我尝试过,但是在控制台中出现错误:“NetworkError:403 FORBIDDEN - ...”

What's the best practice?

什么是最佳做法?

Thanks a lot for your help.

非常感谢你的帮助。

2 个解决方案

#1


1  

You should include CSRF token in your request (or decorate your register method with csrf_exempt - what I don't recommend).

您应该在请求中包含CSRF令牌(或使用csrf_exempt修饰您的注册方法 - 我不建议这样做)。

Just take a look to this example https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

请看一下这个例子https://docs.djangoproject.com/en/dev/ref/csrf/#ajax


As Daniel Roseman has mentioned in comments, you should use GET method for your purposes. It's correct from semantic view-point of HTTP methods. Read more Here

正如Daniel Roseman在评论中提到的那样,你应该使用GET方法。从HTTP方法的语义角度来看,这是正确的。阅读更多

#2


0  

this should work

这应该工作

  $.ajax({
     csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,

                        url: '',
                        data: 'username='+value,
                        type: 'POST',
                        success: function(data){
                            console.log(data);
                        }
                    });

#1


1  

You should include CSRF token in your request (or decorate your register method with csrf_exempt - what I don't recommend).

您应该在请求中包含CSRF令牌(或使用csrf_exempt修饰您的注册方法 - 我不建议这样做)。

Just take a look to this example https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

请看一下这个例子https://docs.djangoproject.com/en/dev/ref/csrf/#ajax


As Daniel Roseman has mentioned in comments, you should use GET method for your purposes. It's correct from semantic view-point of HTTP methods. Read more Here

正如Daniel Roseman在评论中提到的那样,你应该使用GET方法。从HTTP方法的语义角度来看,这是正确的。阅读更多

#2


0  

this should work

这应该工作

  $.ajax({
     csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,

                        url: '',
                        data: 'username='+value,
                        type: 'POST',
                        success: function(data){
                            console.log(data);
                        }
                    });