2013-03-09 3 views
1

몇 일 동안이 문제에 좌절감을 느껴서 도움이 될지 궁금해졌습니다. 저는 Ajax를 처음 사용하고 Django (Django Userena)에 로그인하기 위해 로그인 폼에서 데이터를 게시하려고합니다. 그러나 데이터를 게시하려고하면 alert()가 [object object]로 데이터에 오류를 표시합니다. POST가 실행되기 전에 취소되기 때문에 네트워크 오류 코드가 표시되지 않습니다.Django 데이터 발행물 Ajax POST 양식

데이터를 보내고 전체 JSON 배열을 보내지 않는 방법이 있습니까? 아니면 장고보기 백엔드에서 구문 분석해야합니까? 이 코드를 현명하게 수행하는 가장 좋은 방법은 무엇입니까? 고마워요!

아약스 코드 : Index.html을

$('#login').submit(function(){ 

    $.ajax({ 

     url: 'http://127.0.0.1:8000/accounts/signin/', 
     type: 'POST', 
     data: { 
      csrfmiddlewaretoken: '{{csrf_token}}', 
      identification: $("#id_identification").val(), 
      password: $("#id_password").val(), 
      }, 
     success: function() { 
      alert('Test'); 
      $('#datadisplay').append("<h2>It worked</h2>"); 
     }, 
     error: function(errorThrown){ 
      console.log(errorThrown); 
      alert('Error'); 
      alert(errorThrown); 
     } 
    }); 
}); 

양식

<form name="login" id="login" action=""> 
    <fieldset> 
      <label for="id_identification">Email or username</label> 
      <input class="required" id="id_identification" maxlength="75" name="identification" type="text" /> 

      <label for="id_password">Password</label> 
      <input class="required" id="id_password" name="password" type="password" /> 

      <input type="submit" name="submit" class="loginbutton" value="Login" /> 
     </fieldset> 
    </form> 

장고 - Userena

에서 views.py 아래

는 관련 코드,210
@secure_required 
def signin(request, auth_form=AuthenticationForm, 
      template_name='userena/signin_form.html', 
      redirect_field_name=REDIRECT_FIELD_NAME, 
      redirect_signin_function=signin_redirect, extra_context=None): 
    """ 
    Signin using email or username with password. 

    Signs a user in by combining email/username with password. If the 
    combination is correct and the user :func:`is_active` the 
    :func:`redirect_signin_function` is called with the arguments 
    ``REDIRECT_FIELD_NAME`` and an instance of the :class:`User` who is is 
    trying the login. The returned value of the function will be the URL that 
    is redirected to. 

    A user can also select to be remembered for ``USERENA_REMEMBER_DAYS``. 

    :param auth_form: 
     Form to use for signing the user in. Defaults to the 
     :class:`AuthenticationForm` supplied by userena. 

    :param template_name: 
     String defining the name of the template to use. Defaults to 
     ``userena/signin_form.html``. 

    :param redirect_field_name: 
     Form field name which contains the value for a redirect to the 
     succeeding page. Defaults to ``next`` and is set in 
     ``REDIRECT_FIELD_NAME`` setting. 

    :param redirect_signin_function: 
     Function which handles the redirect. This functions gets the value of 
     ``REDIRECT_FIELD_NAME`` and the :class:`User` who has logged in. It 
     must return a string which specifies the URI to redirect to. 

    :param extra_context: 
     A dictionary containing extra variables that should be passed to the 
     rendered template. The ``form`` key is always the ``auth_form``. 

    **Context** 

    ``form`` 
     Form used for authentication supplied by ``auth_form``. 

    """ 
    form = auth_form() 

    if request.method == 'POST': 
     form = auth_form(request.POST, request.FILES) 
     if form.is_valid(): 
      #identification, password, remember_me = (form.cleaned_data['identification'], 
                #form.cleaned_data['password'], 
                #form.cleaned_data['remember_me']) 
      identification, password = (form.cleaned_data['identification'], form.cleaned_data['password'])  

      user = authenticate(identification=identification, 
           password=password) 
      if user.is_active: 
       login(request, user) 
       if remember_me: 
        request.session.set_expiry(userena_settings.USERENA_REMEMBER_ME_DAYS[1] * 86400) 
       else: request.session.set_expiry(0) 

       if userena_settings.USERENA_USE_MESSAGES: 
        messages.success(request, _('You have been signed in.'), 
            fail_silently=True) 

       # Whereto now? 
       redirect_to = redirect_signin_function(
        request.REQUEST.get(redirect_field_name), user) 
       return HttpResponseRedirect(redirect_to) 
      else: 
       return redirect(reverse('userena_disabled', 
             kwargs={'username': user.username})) 

    if not extra_context: extra_context = dict() 
    extra_context.update({ 
     'form': form, 
     'next': request.REQUEST.get(redirect_field_name), 
    }) 
    return ExtraContextTemplateView.as_view(template_name=template_name, 
              extra_context=extra_context)(request) 

AuthenticationForm

class AuthenticationForm(forms.Form): 
    """ 
    A custom form where the identification can be a e-mail address or username. 

    """ 
    identification = identification_field_factory(_(u"Email or username"), 
                _(u"Either supply us with your email or username.")) 
    password = forms.CharField(label=_("Password"), 
           widget=forms.PasswordInput(attrs=attrs_dict, render_value=False)) 
    remember_me = forms.BooleanField(widget=forms.CheckboxInput(), 
            required=False, 
            label=_(u'Remember me for %(days)s') % {'days': _(userena_settings.USERENA_REMEMBER_ME_DAYS[0])}) 

    def __init__(self, *args, **kwargs): 
     """ A custom init because we need to change the label if no usernames is used """ 
     super(AuthenticationForm, self).__init__(*args, **kwargs) 
     # Dirty hack, somehow the label doesn't get translated without declaring 
     # it again here. 
     self.fields['remember_me'].label = _(u'Remember me for %(days)s') % {'days': _(userena_settings.USERENA_REMEMBER_ME_DAYS[0])} 
     if userena_settings.USERENA_WITHOUT_USERNAMES: 
      self.fields['identification'] = identification_field_factory(_(u"Email"), 
                     _(u"Please supply your email.")) 

    def clean(self): 
     """ 
     Checks for the identification and password. 

     If the combination can't be found will raise an invalid sign in error. 

     """ 
     identification = self.cleaned_data.get('identification') 
     password = self.cleaned_data.get('password') 

     if identification and password: 
      user = authenticate(identification=identification, password=password) 
      if user is None: 
       raise forms.ValidationError(_(u"Please enter a correct username or email and password. Note that both fields are case-sensitive.")) 
     return self.cleaned_data 
+1

JSON 배열을 POST 할 수있는 코드가 표시되지 않습니다. AJAX 요청에 대한 응답 코드는 무엇입니까? '{{csrf_token}}'이 비어있을 수 있습니까? – jpic

+0

@ csrf_exempt를 사용하여 임시로 csrf 확인을 제거하여 다른 문제가 있는지 확인할 수도 있습니다. –

+0

응답 해 주셔서 감사합니다. 완료되기 전에 오류 코드가 종료되기 때문에 응답 코드를 얻을 수 없습니다. 위 코드의 콘솔은 "Object {readyState : 0, getResponseHeader : function, getAllResponseHeaders : function, Set requestHeader : function, overrideMimeType : function ...}"을 출력하지만 마지막 대화 상자를 닫으면 콘솔이 종료되고 지워집니다. \t 양식이 장고를 통해 표시되는 것이 아니라 외부 html 양식으로 표시 될 때 어떻게 양식에 csrf_token을 넣을 수 있습니까? – Jack

답변