Django Custom Login - Form is valid but no error

django custom login page
django custom permissions
django login
django custom user model
django login session
django logout
django custom user login
django-login with email or username

I'm currently trying to figure out how to customize the base Django user login functionality to add e.g. simple-captcha.

I have subclassed "AuthenticationForm" from django.contrib.auth.forms which first looks great, but if I try to login I'm simply not able to.

I have already debugged the code and currently i only get:

response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: init() takes 1 positional argument but 2 were given

accounts/views.py:

...

login form of django.contrib.auth.forms subclassed (copied) to accounts/forms.py:

...

urls.py:

...

There are a few things wrong here.

The main one is that you've overridden the class init signature so that the first positional argument is request, but you pass the POST data in that position; therefore, the form will never be bound and never valid.

Secondly if the form is invalid you re-instantiate it for some reason, so the template will never show any validation errors. Unless you have a really good reason you should stick to the standard form handling structure shown in the docs.

Putting those together:

def login (request):
    if request.method == 'POST':
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.INFO, "You are now logged-In, welcome")
            return redirect(reverse('post_list'))
    else:
        form = LoginForm(request)

        args = {'form': form}
    return render(request, 'registration/login.html', args)

Note, you don't need the second else block; the single one here is aligned with the first if, and the final return is hit in both cases.

Django Custom Login - Form is valid but no error - django - iOS, I have subclassed "AuthenticationForm" from django.contrib.auth.forms which first looks great, but if I try to login I'm simply not able to. I have already debugged� See, how it probably should be is something like this, You request the login form, put in your credentials, you authenticate in the views, if there are any errors you put them in messages and redirect to same view i.e. your login page, this way you will have one message in the form, because on the authentication failure, you will then be redirecting to same login page with messages.

as Daniel said you update init method of form. so you must pass request as first argument.

second is when you validate user info you must authenticate user with authentication backend. but you saved form data.

if you only want to change authentication form you can use login view like this

see below: urls.py

....
    url(r'^accounts/login/$', auth.login, {'authentication_form': LoginForm}, name='login'),
....

if you use django2 and above you can change it like this. first of all create a class based view extended from django.contrib.auth.views.LoginView in this class set form_class to it like this.

from django.conrtib.auth.views import LoginView
...
class NewLoginView(LoginView):
    form_class = LoginForm

then you must update your urls like this:

...
    url(r'^accounts/login/$', NewLoginView.as_view, name='login'),
...

you must extend your form from django.contrib.auth.forms.AuthenticationForm or you must implement all needed function of this form class.

Using the Django authentication system, Access to view the “add” form and add an object is limited to users with the “add” While custom permissions can be defined within a model's Meta class, you can also user) # Redirect to a success page. else: # Return an 'invalid login' error message. Django provides no default template for the authentication views. I was able to make a message form thing in my last project and I compared the two, but this one just doesn’t work. This is what I see in my logs when I click the submit button: [08/Aug/2020 10:16:00] "GET /user/register/ HTTP/1

I finally found a solution, puuh :D

views.py:

...
from django.contrib.auth import update_session_auth_hash, authenticate, login as customlogin
...

def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST, request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(request, username=username, password=password)
            if user is not None:
                customlogin(request, user)
                # Redirect to a success page.
                return redirect(reverse('post_list'))
        return render(request, 'registration/login.html', {'form': form})
    else:
        return render(request, 'registration/login.html', {'form': LoginForm()})

simply extend the form (Thanks to vorujack)

...
from django.contrib.auth.forms import AuthenticationForm
...
class LoginForm (AuthenticationForm):
    captcha = CaptchaField()

urls.py:

url(r'^accounts/login/$', views_accounts.login, name='login'),

the really stupid part is at the login function "form = LoginForm(request.POST, request.POST)" You really need to pass this for the password and user and beside that and secondary request.POST for the captcha form... Oookay. Anyways, now it works.

Thanks anybody for your help, i really appreciate this community

Form and field validation | Django documentation, There are other things that can also trigger cleaning and validation If, at any time, any of the methods raise ValidationError , the validation stops and that error is raised. Note that any errors raised by your Form.clean() override will not be� Override Django Form.is_valid() For this project I won’t be using Django’s built-in user authentication application . It’s a bit restrictive for my taste (but getting better in Django 1.5 from what I can tell).

when I used vorujack's way made mistake,finally I found a solution

in url

from django.contrib.auth import views as auth_views

path('login/',auth_views.LoginView.as_view(form_class=forms.new_login_form,
    template_name='login.html'), name='login'),

in forms

from django.contrib.auth.forms import AuthenticationForm
class new_login_form(AuthenticationForm):
    captcha = CaptchaField(label='验证码', error_messages={"invalid": "验证码错误"})

    class Meta:
        model = User
        fields = ('username', 'password',)

Form handling with class-based views, Initial GET (blank or prepopulated form); POST with invalid data (typically redisplay form with errors); POST with valid data (process the data and typically redirect) When specifying a custom form class, you must still specify the model, even Join a Group � Contribute to Django � Submit a Bug � Report a Security Issue� That way, the form instance, on which is_valid was called, is passed to the template, and it has a chance to display the errors. Only if the form is valid, the user is redirected. If you want to be fancy, add a message using the messages framework before redirecting. If you want it a little bit more concise:

Django's Forms - Python Django Tutorials, Form class fields have built-in validation, depending on the field type, and an the output that Django has created your form elements for you without you having to Finally, if form validation fails, Django will create a dictionary of error messages. myclub_root\myclub_site\urls.py 1 from django.contrib import admin 2 from� Note that any errors raised by your Form.clean() override will not be associated with any field in particular. They go into a special “field” (called __all__), which you can access via the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you need to call add_error().

User Authenication and Login — How_To_Tango_With_Django 1 , Note: make sure that 'django.contrib.auth' and 'django.contrib.contenttypes' are In rango/admin.py import UserProfile and register the UserProfile model with admin, i.e. POST) if uform.is_valid() and pform.is_valid(): user = uform.save() # form else: # Return an 'invalid login' error message. print "invalid login details " +� This Python Django Tutorial is ideal for both beginners as well as professionals who want to master the Django Framework. Below are the topics covered in this Python Web Development Django

Django Tutorial Part 9: Working with forms, Creating and handling forms can be a complicated process! already encountered them in the Django Admin site — for example, the screenshot repost the form with error messages to inform users of any invalid fields, handle If this is not a POST request (handled by the else clause) then we create the� When I enter a valid username and password, it just brings up the login page again, with no error messages. ¶ The login cookie isn’t being set correctly, because the domain of the cookie sent out by Django doesn’t match the domain in your browser. Try setting the SESSION_COOKIE_DOMAIN setting to match your domain.

Comments
  • Hey, i just tried your solution but i get: 'LoginForm' object has no attribute 'save'. i guess that i actually dont even need it there. If i remove it, i simply dont get logged in and get redirected to post list.
  • you does not logged in. you only check user info and redirect to specific user. check in your view if request.user exists and is a authenticated user or not.
  • @ vorujack, my view now looks like the post from Daniel Roseman. Can you please post you solution?
  • >>'LoginForm' object has no attribute 'save'<< What do i have to change at the form? Sry im still a beginner :(
  • I update this answer but you view old one because Daniel not accept it
  • login() got an unexpected keyword argument 'authentication_form'
  • witch version of Django do you use
  • Django 2.1 (current)
  • Beside that, this solution is quite not parical because i won't be able to add captcha field this way. to use a captcha from e.g. django-simple-captcha you need to implement it into a form directly, thats why i want to sub-class this ;)
  • my solution based in django2.x. i update solution for django2.1
  • form = LoginForm(request.POST, request.POST). What is LoginForm? Whyt are you passing the POST twice?