login with ajax,jquery – login form with ajax and django – Stack Overflow

  • Post author:
  • Post category:其他


My app has a the login option, i am trying when the user sumbit the login form, this validate and if is not right say something like user and password doesnt exist, but without my main page reload or redirect to another page, the login form is in the same index page

view.py

@ajax_request

def index(request):

notifi = Notificaciones.objects.filter(user=request.user.id, Estado=False)

if request.method == ‘POST’:

formlog = LoginUserForm(request.POST, request.FILES)

if formlog.is_valid():

cleaned_data = formlog.clean_data

username = cleaned_data.get(‘username’)

password = cleaned_data.get(‘password’)

user = authenticate(nombre_de_usuario=username, password=password)

if user is not None:

if user.is_active:

login(request, user)

return {“status” : “true”}

else:

return {“status” : “false”, “reason” : “You need to activate your account. Please check your email”}

else:

return {“status” : “false”, “reason” : “Invalid username/password”}

else:

formlog = LoginUserForm()

else:

formlog = LoginUserForm()

if request.method == ‘POST’:

form = RegistroUserForm(request.POST, request.FILES)

if form.is_valid():

cleaned_data = form.cleaned_data

username = cleaned_data.get(‘username’)

email = cleaned_data.get(’email’)

password = cleaned_data.get(‘password’)

user_model = MiUsuario.objects.create_user(nombre_de_usuario=username, email=email, password=password)

user_model.save()

else:

form = RegistroUserForm()

else:

form = RegistroUserForm()

context = {

‘formlog’ : formlog,

‘form’: form,

‘notifi’: notifi,

‘year’ : datetime.now().year,

}

return render(request,’app/index.html’,context)

i am using the Ajax from the views

form.py

class LoginUserForm(AuthenticationForm):

“””Authentication form which uses boostrap CSS.”””

username = forms.CharField(label=_(“”),max_length=254,widget=forms.TextInput({‘class’: ‘form-control’,’placeholder’: ‘Nombre de usuario’}))

password = forms.CharField(label=_(“”),widget=forms.PasswordInput({‘class’: ‘form-control’,’placeholder’:’Contraseña’}))

def clean_username(self):

username = self.cleaned_data[‘username’]

if MiUsuario.objects.filter(nombre_de_usuario!=username):

raise forms.ValidationError(‘Nombre de usuario no existe.’)

return username

def clean_password(self):

password = self.cleaned_data[‘password’]

if MiUsuario.objects.filter(password!=password):

raise forms.ValidationError(‘Contraseña incorrecta.’)

return password

login.html

{% csrf_token %}

{

{ formlog.username }}

{%if form.errors %}

{

{forms.ValidationError}}

{% endif %}

{

{ formlog.password }}

{%if form.errors %}

{

{forms.ValidationError}}

{% endif %}

Recordar?

when the informations is wrong redirec to /login, but no validate the inhow can i do the form validate before it reload the page?.