2012-12-03 3 views
0

대화 상자 안에있는 로그인 폼을 만들었습니다. 그것은 아약스없이 예상대로 작동합니다. 문제는 대화 상자를 닫기 전에 로그인 양식의 유효성을 검사하고 싶습니다. 지금 누군가가 제출을 클릭하면 대화 상자가 닫힙니다. 로그인이 잘되면 오류가 발생하지만 오류가 발생하면 로그인을 다시 클릭하여 문제가 있는지 확인해야합니다. 따라서 대화 상자를 닫기 전에 jquery를 구현하여 데이터의 유효성을 검사하려고합니다.Django Jquery 로그인 양식

템플릿

 <a id="login_div" onclick="toggleOverlay();" stlye="color:blue; cursor:pointer;">login or register</a>         
76  <div class="overlay">                             
77   <div class="wrap-outer">                           
78    <div class="wrap">                           
79     <div class="my-dialog">                         
80    <a style="color:blue; cursor:pointer;" onclick="toggleOverlay();">Close</a>             
81                                    
82    <form id="login_form" name="login_form" action="" method="post">                
83                                    
84                                    
85     <h3 id="login_header">Login</h3>                       
86                                    
87     <label id="login_username">Username:</label>                    
88     <label id="login_form_username">{{ request.login_form.username }}< /label>             
89     <label id="login_password" for="password">Password:</label>                
90     <label id="login_form_password">{{ request.login_form.password }} </label>             
91                                    
92      {% csrf_token %}                           
93                                    
94     <input id="login_button" type="submit" name="login_name" value="login" />             
95     <input type="hidden" id="request_path" name="next" value="{{ request.path }}"/>           
96                                    
97    </form>   

JQuery와

1 $(window).load(function(){                             
2 $('#login_form').submit(function(e){                           
3 var request_url = document.getElementById('#request_path')                     
4   $.ajax({                               
5    type:"POST",                              
6    url: request_url,                            
7    data:$('#register_form').serialize(),                       
8    error: function(xhr, ajaxOptions, thrownError){ alert(thrownError); },               
9    success: function(data){}                          
10    });                                
11  e.preventDefault();                              
12 });                                   
13 }); 

보기

13  def process_request(self, request):                          
14                                    
15   # if the top login form has been posted                        
16   if request.method == 'POST':                           
17                                    
18    # validate the form                            
19    lform = AuthenticationForm(data=request.POST)                     
20    if lform.is_valid():                            
21                                    
22     # log the user in                           
23     django_login(request, lform.get_user())                      
24     return HttpResponseRedirect(request.REQUEST.get('next', '/'))                
25                                    
26                                    
27     # if this is the logout page, then redirect to/                   
28     # so we don't get logged out just after logging in                   
29    else:                               
30     lform                              
31                                    
32   else:                                
33    lform = AuthenticationForm(request)                        
34                                    
35   # attach the form to the request so it can be accessed within the templates               
36   request.login_form = lform   

TL; DR은 : 나는를 확인하고 싶습니다 jquery를 사용하여 로그인 양식을 만들고 확인이 완료되면 대화 상자를 닫으십시오.

답변

1

내장 Django 로그인보기를 활용하고 유효성 검사 오류를 JSON으로 반환하면 jQuery를 사용하여 표시 할 수 있습니다. 당신은 몇 가지를 수행해야합니다

...

상속에서 AuthenticationForm 내장하고 JSON으로 양식 오류를 반환하는 방법을 제공한다. JSON에 오류가 있는지 확인하고 오류를 반복하여 대화 상자의 HTML에 추가하십시오.

[뻔뻔스러운 플러그] "AjaxForm/ModelForm"기본 클래스를 살펴보고 "errors_as_json"이라는 추가 메서드를 제공합니다. 또한 오류를 표시하는 방법을 보여주기위한 jQuery 샘플 코드가 있습니다. 코딩

http://djangosnippets.org/snippets/2393/

해피.

+0

+1 놀라운 해결책입니다. 나는 이것이 가능하다는 것을 전혀 몰랐다. 나는이 코드를 이해하지 못한다. if (errors .__ all__! == undefined) { form.append (errors .__ all all__); }' – Houman

+1

감사합니다. 그것은 비 필드 오류가 있는지 찾고, 만약 그렇다면 양식에 추가합니다. – Brandon