0

I have inserted data using User.objects.create() to the the User model and I cannot seem to login using the correct email and password. Whenever I try to Django always returns "wrong username or password" even though I have checked that the user exist using Django ORM.

However, if I register using the link on the webpage, I can login but it created a user with a blank username so I can only create one user, change the username using Django ORM, and then create another one. Is there anything I did wrong? Thanks in advance

Here is my User model:

from django.contrib.auth.models import AbstractUser, UserManager
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _


class MyUserManager(UserManager):

 def create_user(self, *args, **kwargs):
     """
     Set username field as email.
     """
     kwargs['email'] = self.normalize(kwargs['email'])
     kwargs['username'] = self.normalize(kwargs['email'])
     return super(MyUserManager, self).create_user(*args, **kwargs)


@python_2_unicode_compatible
class User(AbstractUser):
    ADMIN_AREA = 'aa'
    FINANCE = 'fn'
    RELATIONSHIP_MANAGER = 'rm'
    BUSINESS_MANAGER = 'bm'
    SENIOR_BUSINESS_MANAGER = 'sbm'
    ADMIN_INTERNAL = 'brm'

    POSITION_CHOICES = {
        (ADMIN_INTERNAL, 'Admin Internal'),
        (SENIOR_BUSINESS_MANAGER, 'Senior Business Manager'),
        (BUSINESS_MANAGER, 'Business Manager'),
        (RELATIONSHIP_MANAGER, 'Relationship Manager'),
        (FINANCE, 'Finance'),
        (ADMIN_AREA, 'Admin Area')
    }
    name = models.CharField(_('Nama Lengkap'), blank=True, max_length=255)
    phone = models.CharField('Nomor telepon', blank=True, max_length=20)
    phone_alt = models.CharField('Nomor telepon alternatif', blank=True, max_length=20)
    date_of_birth = models.DateField('Tanggal lahir', null=True)
    leader = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True)
    email = models.EmailField(max_length=255, unique=True)
    position = models.CharField('Posisi', max_length=3, choices=POSITION_CHOICES, blank=True)
    branch = models.ForeignKey(Branch, on_delete=models.PROTECT, blank=True, null=True)

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []

    def get_all_children(self, include_self=True):
         """Get all relationship manager under one user until second level."""
        childs = User.objects.filter(leader=self)
        if include_self:
        childs = User.objects.filter(Q(id=self.id) | Q(leader=self))

        return childs

    objects = MyUserManager()

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'email': self.email})

This is the script I used to insert the data into the model. Basically what I did is import a csv file and create a user based on the items in the file

import csv
from pertama.users.models import User


with open('zz_supporting_files/data.csv') as csvfile:
 reader = csv.DictReader(csvfile)
 password = "first123"
 for row in reader:
  name = row['NAMA']
  if row['EMAIL'] == "":
   email = name.split(' ')[0].lower() + "@firstone.com"
  else:
   email = row['EMAIL']
  if row['JABATAN'] == "MARKETING":
   position = "rm"
  else:
   position = "bm"
  print(name, email, password, position)  # for debugging
  user = User.objects.create(
   name=name,
   email=email,
   password=password,
   username=email,
   position=position,
  )
  user.save()
User.objects.all()  # Debugging only

EDIT: Inserted the code for CSV file

William Tekimam
  • 91
  • 1
  • 10

1 Answers1

2

You just need to tweak your command to User.objects.create_user() as this will take care of setting password correctly and you will be able to login your webpage.

Don't use User.objects.create()

The correct set of commands should be:

$  pyhton manage.py shell

Then in shell:

 >>> from django.contrib.auth.models import User
 >>> user=User.objects.create_user('foo', password='bar')
 #Only if you want user to have superuser access, else skip this
 >>> user.is_superuser=True
 >>> user.is_staff=True
 >>> user.save()
ans2human
  • 2,300
  • 1
  • 14
  • 29
  • Ah! I see. But using create() the data is also inserted into the model. What's the difference? – William Tekimam Jul 27 '18 at 08:12
  • @WilliamTekimam brother, it is explained in detail here - https://stackoverflow.com/questions/11544398/user-manager-methods-create-and-create-user – ans2human Jul 27 '18 at 08:19
  • @WilliamTekimam Brother, if your query has been resolved you may support this answer by checking the tick. Thankyou – ans2human Jul 27 '18 at 09:22