2

i am a beginner in django. I am working on a project in which customer and companies have their own accounts the models.py is:

class Company_SignUp(models.Model):
   comp_name = models.CharField(_('Company Name'), max_length=30)
   email = models.EmailField(_('E-mail'), unique=True)
   raise forms.ValidationError("This email address already exists.")
   password1 = models.CharField(_('Password'), max_length=128)
   password2 = models.CharField(_('Confirm Password'), max_length=30)

   def __unicode__(self):
       return smart_unicode(self.comp_name)

class Customer_SignUp(models.Model):
   cust_name = models.CharField(_('Customer Name'), max_length=30)
   email = models.EmailField(_('E-mail'), unique=True)
   password1 = models.CharField(_('Password'), max_length=128)
   password2 = models.CharField(_('Confirm Password'), max_length=30) 

   def __unicode__(self):
       return smart_unicode(self.cust_name)

my forms.py is:

class Company(forms.ModelForm):
    class Meta:
        model = Company_SignUp
        widgets = {
          'password1': forms.PasswordInput(),
          'password2': forms.PasswordInput(),
        }
        fields = ('email','password1','password2','comp_name')

    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in       self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two password fields did not match."))
            elif len(self.cleaned_data['password1']) < 8:
                raise forms.ValidationError(_("The password must be 8 characters long."))

        return self.cleaned_data

class Customer(forms.ModelForm):
    class Meta:
        model = Customer_SignUp
        widgets = {
            'password1': forms.PasswordInput(),
            'password2': forms.PasswordInput(),
        }  
    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two password fields did not match."))
            elif len(self.cleaned_data['password1']) < 8:
              raise forms.ValidationError(_("The password must be 8 characters long."))

        return self.cleaned_data

how will i authenticate a company or a customer using their email and passwords. i tried authenticate() but it doesn't work. also how will i check during registration , the email address given already exists

ok now i created a backend which is: from django.contrib.auth.models import User from prmanager.models import Company_SignUp, Customer_SignUp

class EmailBackend(object):
    def authenticate(self, username=None, password=None):
        try:
            o = Company_SignUp.objects.get(email=username, password1=password)
        except Company_SignUp.DoesNotExist:
            try:
                o = Customer_SignUp.objects.get(email=username, password1=password)
            except Customer_SignUp.DoesNotExist:
                return None
        return User.objects.get(email=o.email)
   def get_user(self, user_id):
       try:
          return User.objects.get(pk=user_id)
       except User.DoesNotExist:
           return None

But now i cannot login to admin page using superuser credentials. what should i do

1 Answer 1

2

Models

Consider extending the User model from django.contrib.auth.models like so. If you don't want to do this, skip to the next section (Authentication).

from django.contrib.auth.models import User

class Customer(User):
    # extra fields

The User model has common fields such as username,first_name,last_name,email, etc. You only need to specify any extra attributes your model may have.

The Django docs suggest extending AbstractBaseUser, which may work for you too.

Read more here: https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#extending-the-existing-user-model

Authentication

For email-based authentication, you need to write your own authentication backend: https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#writing-an-authentication-backend

Once you have that in place, you need to accept email / password and authenticate using authenticate and login.

from django.contrib.auth import authenticate, login

def my_view(request):
    email = request.POST['email']
    password = request.POST['password']
    user = authenticate(email=email, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            # Return a 'disabled account' error message
    else:
        # Return an 'invalid login' error message.

The above snippet is from the docs and I have modified it to fit your use-case.

More about authentication in Django: https://docs.djangoproject.com/en/1.7/topics/auth/default/#how-to-log-a-user-in

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.