title: Custom Authentication with Custom User in django?
body: <p>I know there is documentation for this question here <a href="https://docs.djangoproject.com/en/1.9/topics/auth/customizing/" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/auth/customizing/</a>, however I need some clarification on my use case.</p>
  
  <p>I basically have an api that I created. What this api does is submit user form data to an external url, and once submitted, the data is saved to that external urls database.</p>
  
  <p>I can then get a specific user through another api call. The user is returned as an object. Now I am trying to log that user in on my end using the django.contrib.auth through my system but what I have isn't working.</p>
  
  <p>Here is my process:</p>
  
  <p>A. I added a custom authentication backend to my settings.py file</p>
  
  <pre><code>AUTHENTICATION_BACKENDS =(
      'new_app.backends.SettingsBackend',
      'django.contrib.auth.backends.ModelBackend',
  )
  </code></pre>
  
  <p>B. In my new_app's backend file, I have the following code:</p>
  
  <pre><code>class SettingsBackend(object):
      def authenticate(self, username=None, password=None):
              if username and password:
                  user = api.get_user()
                  #add pk to user object to satisfy django error warning
                  user.pk = user.unique_field
                  return user
              return None
  
      def get_user(self, user_id):
          try:
              if self.user.pk == user_id:
                  return self.user
          except:
              return None
  </code></pre>
  
  <p>In a signin view, I am trying to log the user in using this:</p>
  
  <pre><code>def login_user(request, username, password):
      from django.contrib import auth 
      if not username and password:
          raise ValueError("Invalid username and password")
  
      auth_user = auth.authenticate(username=username, password=password)
  
      if auth_user is None:
          raise ValueError("Invalid username and password")
  
      auth.login(request, auth_user)
      return auth_user
  </code></pre>
  
  <p>I get the error saying:</p>
  
  <pre><code>'api.get_user()' object has no attribute 'save'
  </code></pre>
  
  <p>The error is occuring on the <code>auth.login(request, auth_user)</code> line.</p>
  
  <p>I think the reason is because the django.contrib.auth thinks my user object is a django model. So, the question is how should I tackle this to make it work given my scenario? Thanks for the time.</p>