Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django custom login page

I have a custom Django login page. I want to throw an exception when username or password fields are empty. How can I do that?

My view.py log in method :

def user_login(request):
    context = RequestContext(request)
    if request.method == 'POST':
        # Gather the username and password provided by the user.
        # This information is obtained from the login form.
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        print("auth",str(authenticate(username=username, password=password)))

        if user:
            # Is the account active? It could have been disabled.
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/')
        else:
            return HttpResponse("xxx.")
    else:
        # Bad login details were provided. So we can't log the user in.
        print ("Invalid login details: {0}, {1}".format(username, password))
        return HttpResponse("Invalid login details supplied.")
    else:
        return render_to_response('user/profile.html', {}, context)

I tried this and it didn't work: This is forms.py

def clean_username(self):
    username = self.cleaned_data.get('username')
    if not username:
        raise forms.ValidationError('username does not exist.')
like image 430
chazefate Avatar asked Mar 03 '16 13:03

chazefate


2 Answers

The correct approach is to use forms, instead of fetching the variables directly from request.POST. Django will then validate the form data, and display errors when the form is rendered in the template. If a form field is required, then Django will automatically display an error when the field is empty, you don't even need to write a clean_<field_name> method for this.

Django already has a built in login view. The easiest approach is to use this rather than writing your own. If you still want to write your own view, you will still find it useful to look at how Django does it.

like image 143
Alasdair Avatar answered Sep 29 '22 05:09

Alasdair


You can use login view, which is provided by Django. So your login.html should look like that example.

<form class="login" method="POST" action="/login/">

  {% csrf_token %}

  {{form.as_p}}

  <li><input type="submit" class="logBut" value="Log in"/></li>
  </form>

And remember urls.py !

url(r'^login/$','django.contrib.auth.views.login', {'template_name': '/login.html'}),
like image 33
p3y4m Avatar answered Sep 29 '22 06:09

p3y4m