0

I am able to register accounts and upload the data towards the MYSQL database, but the accounts are not "authentication"

views.py

from django.core.urlresolvers import reverse_lazy
from django.views.generic import FormView, TemplateView
from django.shortcuts import redirect, get_object_or_404, render, render_to_response
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.contrib import messages, auth
from django.http import HttpResponseRedirect, HttpResponse
from django.core.context_processors import csrf
from mongoengine.queryset import DoesNotExist

from .forms import *

class RegisterView(FormView):
    template_name = 'registration/register.html'
    form_class = UserCreationForm
    success_url = reverse_lazy('registered')

    def form_valid(self, form):
        form.save()
        return FormView.form_valid(self, form)

register = RegisterView.as_view()


class RegisteredView(TemplateView):
    template_name = 'registration/registered.html'

registered = RegisteredView.as_view()

def login(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('registration/auth.html', c)

def auth_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
             login(request, user)
        else:
          return HttpResponseRedirect('/inactive')
     else:
          return HttpResponseRedirect('/invalid')

def loggedin(request):
    return render_to_response('registration/hello.html', 
                          {'full_name': request.user.username})

def invalid_login(request):
    return render_to_response('registration/hello.html')

Auth_view() is what handles the logging in.

Basically no matter what I do it always hits "except Exception:" with the unknown error flag. I feel like it's not even connecting with the MYSQL db and "authenticating"

EDIT: Updated Views.py/auth_view()

UserCreation form (forms.py)

   class UserCreationForm(forms.Form):
        error_messages = {
            'duplicate_username': _("A user with that username already exists."),
            'password_mismatch': _("The two password fields didn't match."),
        }
        username = forms.RegexField(label=_("Username"), max_length=30,
            regex=r'^[\w.@+-]+$',
            help_text=_("Required. 30 characters or fewer. Letters, digits and "
                      "@/./+/-/_ only."),
        error_messages={
              'invalid': _("This value may contain only letters, numbers and "
                          "@/./+/-/_ characters.")})
    email = forms.EmailField(label=_("Email"), max_length=254,
        help_text=_("Required valid email. 254 characters or fewer."),
        error_messages={
            'invalid': _("This value may contain only valid email address.")})
    password1 = forms.CharField(label=_("Password"),
        widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
        widget=forms.PasswordInput,
        help_text=_("Enter the same password as above, for verification."))

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
             User._default_manager.get(username=username)
         except User.DoesNotExist:
             return username
        raise forms.ValidationError(
            self.error_messages['duplicate_username'],
           code='duplicate_username',
        )

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

    def save(self):
        user = User._default_manager.create_user(
             username=self.cleaned_data['username'],
             email=self.cleaned_data['email'],
             password=self.cleaned_data["password1"])
        return user

EDIT 2:

spvceman
  • 53
  • 1
  • 8

3 Answers3

0

Well I think you have to use the authentication from django:

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

See this page for more information on how to use django authentication:

https://docs.djangoproject.com/en/dev/topics/auth/default/#auth-web-requests

And btw if you can register users it means you django app is well connected to the database, the problem must be somewhere else.

Freelancer
  • 4,459
  • 2
  • 22
  • 28
  • I did that as well, I updated the code with the changes including that line you mentioned, still doesnt authenticate. – spvceman Jul 16 '14 at 15:06
  • @spvceman are you sure users are well registered in database ? Can you provide the UserCreationForm class ? – Freelancer Jul 16 '14 at 15:09
0

I think problem is here:

def form_valid(self, form):
        form.save()
        return Super(RegisterView, self).form_valid(form) #instead of FormView.form_valid(self, form)
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Registering accounts are fine. t gets added to the db under "auth_users" table. Just for somereason when logging in its not able to authenticate. hence ` user = authenticate(username=username, password=password)` – spvceman Jul 16 '14 at 16:34
  • I see, what does the exception say when you try to authenticate? – ruddra Jul 16 '14 at 17:06
  • 'AnonymousUser' object has no attribute 'backend' – spvceman Jul 16 '14 at 17:20
  • That is weird, this problem occurs if you don't use authenticate before using login. reference: http://stackoverflow.com/questions/8321319/anonymoususer-object-has-no-attribute-backend , clearly its not an issue here – ruddra Jul 16 '14 at 17:25
  • Yeah, my apologies, I was basically trying to debug myself doing "return HttpResponse()" annd see the error I get if i put "login(request, user)", but then as you said that will give that error. so instead i put authenticate() in there, and its returning as "None" basically its unable to match usernames and passwords with registered ones in the db for some reason. – spvceman Jul 16 '14 at 17:29
  • check your request.POST['username']/['password']. and I think you should a form to provide login data. :) – ruddra Jul 16 '14 at 17:36
  • I got to work, thanks for all the help, I added "django.contrib.auth.backends.ModelBackend'," to my settings. Pretty stupid mistake by me. But while we are at it, may I ask how do you make it so you can't access pages without logging in first. – spvceman Jul 16 '14 at 17:46
0

So I got it to work :P

In my settings.py files I had to add

django.contrib.auth.backends.ModelBackend',

I am literally an idiot.

spvceman
  • 53
  • 1
  • 8