djangodjango-viewsdjango-formsdjango-authentication

How to use Django-simple-captcha on the admin login page?


I would like to add captcha on my django login form using Django Simple Captcha found here: http://code.google.com/p/django-simple-captcha/

This works great if you create a new form but I'm using the django.contrib.auth.forms the one that comes with django. Any idea how I might be able to implement captcha with the existing django auth views or any ways? Thank you! Please do not suggest using Google reCaptcha.

My urls.py

from  django.contrib.auth import views as auth_views
urlpatterns = [
      path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login') 
      ,...
]

My login.html

<form  class="fadeIn second"  method="post">
    {% csrf_token %}

{{ form.as_p }}

<button   type="submit" class="btn btn-primary"> Login </button>

</form>

My Forms.py

from captcha.fields import CaptchaField

class MyFormCaptcha(forms.Form):
    captcha = CaptchaField()

Solution

  • This video and this GitHub project solved my problem. You can customize the project code according to your needs. For me it is as follows.

    My urls.py

    urlpatterns = [
      ...
        path('captcha/',include('captcha.urls')),
        path('submit',submit,name='submit')
    ]
    

    My forms.py

    from captcha.fields import CaptchaField
    
    class MyForm(forms.Form):
        captcha=CaptchaField()
    

    My login.html

    <form action="/submit" method="post">
        {% csrf_token %}
        <div>
            <label for="fullname">Full Name</label>
            <input type="text" id="fullname" name="fullname">
            </div>
            <br>
         <div>
             <label for="email">Email</label>
             <input type="text" id="email" name="email">
         </div> <br>
            {{form.captcha}}
            <button type="submit">Submit</button>
    </form>
    

    My views.py How to log a user in?

      from django.contrib.auth import authenticate, login    
      def test(request):
           form=MyForm()
    
           return render(request,'captcha/home.html',{'form':form})
    
    def submit(request):
        if request.method == 'POST':
            form=MyForm(request.POST)
            if form.is_valid():
                name=request.POST['fullname']
                email=request.POST['email']
                print('success')
                print(name)
                print(email)
                user = authenticate(request,username=username,password=password)
           if user is not None:
               login(request, user)
               return redirect('/homepage')   # Redirect to a success page.
           
           else:
               # Return an 'invalid login' error message.
                print('fail')
                messages.success(  request,f 'login failed! username or passwoed is wrong!'
                return redirect('login')