All usernames are indicated by the username phrase - django

admin dashboard:
In addition to the admin part, the template is displayed in the same way.
Ever since I customized the accounts section, in all the sections where I have used the username, there is a problem that the usernames are displayed without that name and only by displaying the phrase username.
settings.py:
AUTH_USER_MODEL = 'accounts.CustomUser'
models.py(accounts):
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError("Users must have an email address.")
if not username:
raise ValueError("Users must have a username.")
user = self.model(
email=self.normalize_email(email),
username=username
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email=self.normalize_email(email),
username=username,
password=password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
def get_profile_image_filepath(self, filepath):
return f'images/accounts/profiles/{self.pk}/{"profile.png"}'
class CustomUser(AbstractBaseUser, PermissionsMixin):
class Meta:
permissions = [
('all', 'all of the permissions')
]
first_name = models.CharField(max_length=30, null=True, blank=True)
last_name = models.CharField(max_length=30, null=True, blank=True)
email = models.EmailField(verbose_name='email', max_length=100, unique=True)
username = models.CharField(max_length=55, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
profile_image = models.ImageField(null=True, blank=True, upload_to=get_profile_image_filepath, default='images/accounts/profiles/default_image.jpg')
objects = MyAccountManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.USERNAME_FIELD
def get_profile_image_filename(self):
return str(self.profile_image)[str(self.profile_image).index(f'images/accounts/profiles/{self.pk}/'):]
def get_absolute_url(self):
return reverse("accounts:user_view", args=[str(self.id)])
models.py(news):
class News(models.Model):
class Meta:
permissions = [
('all', 'all of the permissions')
]
ordering = ['-date']
title = models.CharField(max_length=255)
header_image = models.ImageField(null=True, blank=True, upload_to="images/news/header/")
body = RichTextUploadingField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
category = models.ManyToManyField(Category, default='cryptocurrency', related_name='category')
like_news = models.ManyToManyField(AUTH_USER_MODEL, blank=True, related_name='the_news')
unlike_news = models.ManyToManyField(AUTH_USER_MODEL, blank=True, related_name='the_news_unlike')
def total_likes(self):
return self.like_news.count()
def total_unlikes(self):
return self.unlike_news.count()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("news_detail", args=[str(self.id)])
Which part of the code is wrong that shows the username like this?

You need to return self.username, not self.USERNAME_FIELD:
class CustomUser(AbstractBaseUser, PermissionsMixin):
# …
USERNAME_FIELD = 'username'
def __str__(self):
return self.username
or if you want to return the attribute with the USERNAME_FIELD, you can use the getattr(…) function [Python-doc]:
class CustomUser(AbstractBaseUser, PermissionsMixin):
# …
USERNAME_FIELD = 'username'
def __str__(self):
return getattr(self, self.USERNAME_FIELD)

Related

rest_framework.request.WrappedAttributeError: 'AccountManager' object has no attribute 'get'

I am working on my Django project, I am getting this error but i don't really know how to fix it exactly, i have created my custom user model and the user manager
class AccountManager(BaseManager):
def create_user(self, email, fullname=None, birthday=None,zipcode=None, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(Email_Address=self.normalize_email(email),
name=self.normalize_email(email),
Date_of_Birth=birthday,
zipcode=zipcode
)
user.set_password(password)
user.save(using='self._db')
return user
def create_superuser(self, Email_Address, username, password):
user=self.create_user(Email_Address=self.normalize_email(Email_Address), password=password,)
user.is_admin = True
user.is_active = True
user.is_staff = True
user.is_superuser = True
user.save(using='self._db')
class User(AbstractUser):
Email_Address = models.EmailField(verbose_name='email', unique=True, blank=True, null=True)
Date_of_Birth = models.CharField(max_length=30, blank=True, null=True, default=None)
name = models.CharField(max_length=30, blank=True, null=True)
username= models.CharField(max_length=30,unique=True, blank=True, null=True)
zipcode = models.CharField(max_length=30, blank=True, null=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'Email_Address'
objects = AccountManager()
REQUIRED_FIELDS = ['username']
def __str__(self):
return self.username
because i am using rest_framework_simplejwt for authentication i am getting this error when i try to log in
user = self.user_model.objects.get(**{api_settings.USER_ID_FIELD: user_id})
rest_framework.request.WrappedAttributeError: 'AccountManager' object has no attribute 'get'
can anyone please help me with this
According to this section, https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#writing-a-manager-for-a-custom-user-model, you need to extend your custom user manager from BaseUserManager.
In your code you extended from the BaseManager.

Setting password for user model in the admin page

I created a custom User model with multiple roles customers, and employees, where employees also are in different roles: Drivers and administration.
I extended AbstractBaseUser model class to set a customized user model as this:
class UserAccountManager(BaseUserManager):
def create_superuser(self, email, first_name, last_name, password, **other_fields):
other_fields.setdefault("is_staff", True)
other_fields.setdefault("is_superuser", True)
other_fields.setdefault("is_active", True)
other_fields.setdefault("is_driver", True)
other_fields.setdefault("is_customer", True)
other_fields.setdefault("is_responsable", True)
if other_fields.get("is_staff") is not True:
raise ValueError(_("Superuser must be assigned to is_staff."))
if other_fields.get("is_superuser") is not True:
raise ValueError(_("Superuser must be assigned to is_superuser."))
return self.create_user(email, first_name, last_name, password, **other_fields)
def create_user(self, email, first_name, last_name, password, **other_fields):
if not email:
raise ValueError(_("You must provide an email address"))
email = self.normalize_email(email)
user = self.model(email=email, first_name=first_name, last_name=last_name, **other_fields)
user.set_password(password)
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_("Email Address"), unique=True)
first_name = models.CharField(_("First Name"), max_length=150, unique=True)
last_name = models.CharField(_("Last Name"), max_length=150, unique=True)
mobile = models.CharField(_("Mobile Number"), max_length=150, blank=True)
is_active = models.BooleanField(_("Is Active"), default=False)
is_staff = models.BooleanField(_("Is Staff"), default=False)
is_driver = models.BooleanField(_("Is Driver"), default=False)
is_responsable = models.BooleanField(_("Is Responsable"), default=False)
is_customer = models.BooleanField(_("Is Customer"), default=False)
created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False)
updated_at = models.DateTimeField(_("Updated at"), auto_now=True)
objects = UserAccountManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["first_name", "last_name"]
class Meta:
verbose_name = "Account"
verbose_name_plural = "Accounts"
def __str__(self):
return self.first_name
and I created two types of models the extend this model which represent each on a different role and inherit from User model:
class Employee(User):
registration_number = models.PositiveSmallIntegerField(_("Driver Registration Number"), unique=True)
picture = models.ImageField(
verbose_name=_("Driver Pic"), help_text=_("Driver Identity Picture"), upload_to="images/driver/"
)
birth_date = models.DateField(_("Date Birth of the Driver"))
city_id = models.ForeignKey("City", blank=True, null=True, on_delete=models.SET_NULL)
bank_id = models.ForeignKey("Bank", blank=True, null=True, on_delete=models.SET_NULL)
class Meta:
verbose_name = "Employee"
verbose_name_plural = "Employees"
def __str__(self):
return self.first_name + " " + self.last_name
class Customer(User):
company_name = models.CharField(_("Company Name"), max_length=150, unique=True)
website = models.CharField(_("Company website"), max_length=150, unique=True)
mobile_2 = models.CharField(_("Mobile Number"), max_length=150, blank=True)
class Meta:
verbose_name = "Customer"
verbose_name_plural = "Customers"
def __str__(self):
return self.first_name + " " + self.last_name
I want to register the models in the admin.py:
#admin.register(User)
class UserAdmin(admin.ModelAdmin):
pass
admin.site.register(Customer)
admin.site.register(Employee)
the problem is that, when I try to add a user from the admin page, I can't set a password for this user, I have a password field that appear when I want to add a new user in any model, but the field seems to be as any normal InputText, the password is visible when it's tapped, and no password is registered in the database.
I would like to add two type of Employee in the model.py :
class Responsable(Employee):
responsability_type = models.CharField(max_length=4, blank=True)
class Meta:
verbose_name = "Responsable"
verbose_name_plural = "Responsables"
def __str__(self):
return self.first_name + " " + self.last_name
class Driver(Employee):
driving_licence = models.ImageField(
verbose_name=_("Driver Licence"), help_text=_("Driver Licence Picture"), upload_to="images/driver_licence/"
)
driver_licence_expiration_date = models.DateField(_("Expiration Date for Driver Licence"))
class Meta:
verbose_name = "Driver"
verbose_name_plural = "Drivers"
def __str__(self):
return self.first_name + " " + self.last_name
I don't know if it's a good idea to design this models for this kind of roles, I want to avoid getting multiple tables with passwords stored in it.
Don' t use model inheritance like that, especially for the custom User model. Creates a unique model that inherits from AbstractBaseUser, that contains the type of the user and that contains all the fields that you have declared in your current tables:
class User(AbstractBaseUser, PermissionsMixin):
class UserTypes(Enum):
customer = ('cu', 'Customer')
responsable = ('re', 'Responsable')
driver = ('dr', 'Driver')
#classmethod
def get_value(cls, member):
return cls[member].value[0]
user_type = models.CharField(max_length=2, choices=[x.value for x in UserTypes])
# Insert fields that are in common between all user types, for example:
email = models.EmailField(_("Email Address"), unique=True)
# Insert fields that could be None depending on the user type, for example:
company_name = models.CharField(_("Company Name"), max_length=150, unique=True, null=True, blank=True)
Then add this in your settings:
AUTH_USER_MODEL = 'yourappname.User'
Your ModelAdmin for managing users should inherit from UserAdmin to allow password management:
#admin.register(User)
class UserAdmin(UserAdmin):
fieldsets = ((None, {'fields': ('email', 'password', 'user_type', 'company_name')})) # Other fields showed when updating an user
add_fieldsets = ((None, {'fields': ('email', 'password', 'user_type', 'company_name')})) # Other fields showed when creating an user

Using ForeignKey of Django CustomUser giving attribute error

Not using Djnago Default user model. Have created a Custom user model named CustomUser
class CustomUser(AbstractBaseUser):
GENDER_CHOICE = (
('MALE', 'MALE'),
('FEMALE', 'FEMALE'),
)
BLOOD_GROUP_CHOICE = (
('A+', 'A+'),
('B+', 'B+'),
('O+', 'O+'),
('AB+', 'AB+'),
('A-', 'A-'),
('B-', 'B-'),
('O-', 'O-'),
('AB-', 'AB-'),
)
RELIGION_CHOICE = (
('ISLAM', 'ISLAM'),
('HINDU', 'HINDU'),
('CHRISTIANITY', 'CHRISTIANITY'),
('OTHER', 'OTHER'),
)
email = models.EmailField(max_length=60, unique=True, verbose_name='Email')
first_name = models.CharField(max_length=30, verbose_name='First Name')
last_name = models.CharField(max_length=30, verbose_name='Last Name')
gender = models.CharField(_("Employee Gender"),
max_length=6, choices=GENDER_CHOICE, null=True, blank=True)
blood_group = models.CharField(
_("Employee Blood Group"), max_length=3, choices=BLOOD_GROUP_CHOICE, null=True, blank=True)
birth_of_date = models.DateField(
_("Employee Birth Date"), auto_now=False, auto_now_add=False, null=True, blank=True)
#address = models.CharField(_("Employee Address"), max_length=500, null=True, blank=True)
address = models.CharField(_("Employee Address"), max_length=500, null=True, blank=True)
phone_number = PhoneNumberField(null=True, blank=True)
profile_pic = models.ImageField(_("Employee Profile Picture"), upload_to='profile_pic',
height_field=None, width_field=None, max_length=None, null=True, blank=True)
religion = models.CharField(
_("Employee Religion"), max_length=15, choices=RELIGION_CHOICE, null=True, blank=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ('first_name', 'last_name')
objects = CustomUserManager()
def __str__(self):
return self.email
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return self.is_admin
class Meta:
verbose_name_plural = "Shunno ek Users"
Here is my CumstomUser models' CustomUsermanager
class CustomUserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password=None):
if not email:
raise ValueError('You must have an email')
email = email.lower()
first_name = first_name.title()
last_name = last_name.title()
user = self.model(
email = self.normalize_email(email),
first_name = first_name,
last_name = last_name
)
#user.password = password
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, first_name, last_name, password=None):
user = self.create_user(
email = email,
first_name = first_name,
last_name = last_name,
password = password
)
user.is_admin = True
user.is_staff = True
user.save(using=self._db)
return user
This is a model of saving users Quiz answers.
class UserAns(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quiz_user')
quizcat = models.ForeignKey(Category, on_delete=models.CASCADE)
totalq = models.DecimalField(max_digits=5,decimal_places=2)
correcta = models.DecimalField(max_digits=5,decimal_places=2)
def __str__(self):
return self.User.first_name
It is view part where i want to save the data of user answer.
def quizpage(request, slug):
if request.method == 'POST':
# totalquestion
solve = 0
for question in range(1,cat.totalq+1):
entered_answer_questionpk = request.POST.get(str(question))
ans = entered_answer_questionpk[:1]
qpk = int(entered_answer_questionpk[1:])
actualans = Question.objects.get(pk=qpk).correct_answer
if ans == actualans:
solve = solve + 1
# print(user)
usersans = UserAns(totalq=cat.totalq, correcta=solve)
usersans.quizcat = cat
print(request.user)
usersans.user = request.user
usersans.save()
return render(request, 'quiz/quizpage.html',{'questions': questions })
after saving this value in the database, when I click the table name it gives this error:
Django Version: 3.1.3
Exception Type: AttributeError
Exception Value:
'UserAns' object has no attribute 'User'
I can't understand where is my problem.
Your string method is referencing self.User and not self.user.
def __str__(self):
return self.user.first_name
Previous answer:
You should also look through your view that's rendering the page and protect any parts that access userans.user via if hasattr(userans, 'user'): or if userans.user_id:.
Another thing you can do is clean up your data. Your post view looks to be about right. But that page is failing because you have instances that still have the user property with a value of None.Open up a shell manage.py shell, import your UserAns model and see if you have any instances without a user. If you do, determine which user(s) they should map to or delete them.
UserAns.objects.filter(user__isnull=True)

Exception Value: local variable 'other_user' referenced before assignment

So, this is probably just something simple I'm doing wrong here. But basically, I am attempting to simply pass in the pk of the other_user. I tested that the query works correctly, and am indeed printing the other user. Just don't know where to place it correctly in my code so I can pass it to the render part.
local variable 'other_user' referenced before assignment
models.py
class ProfileManager(BaseUserManager):
def create_user(self, username, email,description,photo, password=None):
if not email:
raise ValueError("You must creat an email")
if not username:
raise ValueError("You must create a username!")
if not description:
raise ValueError("You must write a description")
if not photo:
raise ValueError("You must upload a photo")
user = self.model(
email=self.normalize_email(email),
username = username,
description= description,
photo= photo,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email,description,photo, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
description=description,
photo=photo,
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
class Profile(AbstractBaseUser):
class Meta:
swappable = 'AUTH_USER_MODEL'
email = models.EmailField(verbose_name="email")
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
#what I added
description = models.TextField()
photo = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
matches = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='+', blank=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['description','photo','email']
objects = ProfileManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self,app_label):
return True
class Conversation(models.Model):
members = models.ManyToManyField(settings.AUTH_USER_MODEL)
class UserVote(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
voter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='given_vote', on_delete=models.CASCADE)
vote = models.BooleanField(default=False)
class Meta:
unique_together = (('user', 'voter'))
class InstantMessage(models.Model):
sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE )
conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE)
message = models.TextField()
date = models.DateTimeField(verbose_name="Data creation",default=timezone.now(), null=False)
def __unicode__(self):
return self.message
#tests to see if messages are exclusive between sender, receiver (won't work with new model)
#classmethod
def find_messages_exclusive_to_profile(cls,sender,receiver):
#members = receiver AND sender, not receiver or sender
exclusive_conversations = Conversation.objects.filter(members= receiver ).filter(members= sender)
exclusive_messages = InstantMessage.objects.filter(conversation__in=exclusive_conversations)
return exclusive_messages
def message (request, profile_id):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
form.save()
return redirect('dating_app:messages', other_user.id)
else:
conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create()
print(conversation)
other_user = conversation.members.filter(id=profile_id).get()
print(other_user)
form = MessageForm({'sender': request.user, 'conversation': conversation})
context = {'form' : form }
return render(request, 'dating_app/message.html', context)
You can access the ModelForm's instance from form.instance and get value from there.
if form.is_valid():
form.save()
m = form.instance
return redirect('dating_app:messages', m.id)
You are mostly likely to also get the instance while saving it as
m = form.save()

Cannot resolve keyword 'is_active' into field

Trying to make a password reset view. I'm using the auth_views built in views ie PasswordResetView and PasswordResetConfirmView for resetting password. However I was getting this error
Cannot resolve keyword 'is_active' into field. Choices are: active, admin, email, first_name, id, last_login, last_name, logentry, password, staff, timetables
. Tried changing active to is_active and getting this error.
django.core.exceptions.FieldError: Unknown field(s) (active) specified for User
Not able to make migrations
models.py
class User(AbstractBaseUser):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=254, unique=True)
is_active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
def get_first_name(self):
if self.first_name:
return self.first_name
return self.email
def get_last_name(self):
return self.last_name
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.is_active
forms.py
class UserAdminChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'first_name', 'last_name',
'password', 'active', 'admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
Try to change is_active = models.BooleanField(default=True) to active = models.BooleanField(default=True) in your User class, and is_active property
see below
class User(AbstractBaseUser):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=254, unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
#property
def is_active(self):
return self.active