如何在不重新加载页面的情况下显示django消息?

时间:2019-04-13 11:01:41

标签: javascript python json ajax django

我正在构建一个弹出注册表单。并且当出现错误或成功消息时,不想重新加载页面。因为随后弹出式窗体将被关闭。我只想在不重新加载页面的情况下显示消息。

这是我到目前为止所做的

views.py

def signup(request):

if request.method == "POST":

    username = request.POST["username"]
    email =  request.POST["email"].lower()
    password = request.POST["password"]
    password2 = request.POST["password2"]

    try:
        if password2 != password:
            messages.error(request, "password didn't match")
        elif len(password) < 6:
            messages.error(request, "password is too small.")
        elif User.objects.get(email=email):
            messages.error(request, "user with this email already exists")
    except:
        if not (User.objects.filter(username=username).exists()):
            user = User.objects.create_user(username=username, email=email)
            user.set_password(password)
            user.save()
            messages.success(request, "User Created")
        else:
            messages.error(request, "Looks like username already exists")

    django_messages = []

    for message in messages.get_messages(request):
        django_messages.append({
            "level": message.level,
            "message": message.message,
            "tags": message.tags, 
            })

    data = {}
    data['messages'] = django_messages

    return HttpResponse(json.dumps(data), content_type="application/json")
return redirect(request.META['HTTP_REFERER'])

ajax代码

<script type="text/javascript">
$(document).on('submit','#signup_form',function(e){
    e.preventDefault();

    $.ajax({
        type:'POST',
        url:"{% url 'auth_signup' %}",
        data:{

            'username':$('#signup_username').val()
            'email':$('#signup_email').val(),
            'password':$('#signup_password').val(),
            'password2':$('#signup_password2').val(),
            'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
        },
        success:function(data){
            update_messages(data.messages);;
            $(".message").show();

        },

        error:function(data){
            update_messages(data.messages);
            (".message").show();


        }
    });
}); 

<script type="text/javascript">
function update_messages(messages){
$("#msgs").html("");
$.each(messages, function (i, m) {
            $("#msgs").append("<div class='alert "+m.tags+"''><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>"+m.message+"</div>");});}</script>

当我按下提交按钮时。 它应该在那里显示错误或成功消息。但 页面转到网址http://127.0.0.1:8000/signup,仅显示此json字符串。

{“消息”:[{“级别”:40,“消息”:“密码不匹配”,“标签”:“警报危险”}]}

0 个答案:

没有答案