Extending user models in Django saves password publicly - python

The password for newly created users is shown publicly on the admin console models. Why is that and how I do it correctly?
Furthermore, I am not actually able to login with any of the new users created in the Accounts_app. I am able to login only with the python manage.py createsuperuser
I created at the early point in the project.
Here is the models.py
from django.contrib.auth.models import AbstractUser
class ProjectUser(AbstractUser):
def __str__(self):
return self.username
Here is the settings.py
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
]
AUTH_USER_MODEL = 'accounts_app.ProjectUser'
Here is my admin view
To create the user, I click "Add User" in the app admin view.
Here is the apps.py file
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'accounts_app'
Here is the admin.py file
from django.contrib import admin
from accounts_app.models import ProjectUser
# Register your models here.
admin.site.register(ProjectUser)

Although you set ProjectUser to be the AUTH_USER_MODEL, you registered it in the admin as a standard model, not the user one. You need to use the user admin, as shown in the docs, since this takes care of hashing the password:
from django.contrib.auth.admin import UserAdmin
admin.site.register(ProjectUser, UserAdmin)
You'll need to delete and recreate the users you generated via the admin before changing this.

Firstable, what do you want to do, extend or custom the User Model?
If you want to extend... It's enough with a foreign key. For this, the Django project recommends using OneToOneField(User)
In this case, see the link below.
https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#extending-the-existing-user-model
In the other hand, if you want to custom the User model, you must have to do this before doing the migrations. The initial setup must have your customization. You can create an app only for the User Model customization.
In this case, see the links below.
https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#substituting-a-custom-user-model
https://wsvincent.com/django-tips-custom-user-model/
I hope this helped you

Related

Updates to admin.py not reflected in the django admin page

I'm building a django app and the django admin page doesn't seem to be reflecting the changes I make to admin.py. For example if I want to exclude some fields, or customizing the admin change list, nothing changes in the actual page. The only thing that seems to be reflected properly is the fact that I can register the models, and they will show up.
Here's my admin.py
from django.contrib import admin
from .models import Form, Biuletyn, Ogloszenie, Album
class FormAdmin(admin.ModelAdmin):
exclude = ('img',)
class BiuletynAdmin(admin.ModelAdmin):
list_display = ('name', 'date')
class OgloszenieAdmin(admin.ModelAdmin):
fields = ('name', 'date', 'upload')
admin.site.register(Form)
admin.site.register(Biuletyn)
admin.site.register(Ogloszenie)
admin.site.register(Album)
P.S. Please ignore the weird model names. The site is actually in a different language :D
This is how you register your ModelAdmin:
admin.site.register(Form, FormAdmin)
admin.site.register(Biuletyn, BiuletynAdmin)
admin.site.register(Ogloszenie, OgloszenieAdmin)
This how to register your Models:
admin.site.register(Album)
For more details you may refer to Django official documentation at: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#modeladmin-objects
Add admin_class
So for example for the Form model:
admin.site.register(Form, admin_class=FormAdmin)

Check who is logged in Django admin panel

how to check whether the user is logged in or not from admin panel
what are the changes i need to make in models.py and admin.py to achieve this
from django.contrib.auth.models import User
You can't really. Django Contrib Admin doesn't track this information. The most you can get is if User has is_staff or is_superuser to check if they could potentially visit django.contrib.admin interface.
im assuming you have two functions in your views.py
loginUser
logoutUser
create a model with user as foreignkey, for storing logged users
eg. class loggedUsersModel
now in loginUser function
loggedUsersModel(user = request.user).save()
and in logoutUser function
loggedUsersModel(user = request.user).delete()
this will save loggedUsers
and register loggedUsersModel in admin.py using
admin.site.register(loggedUsersModel)

Django CustomUser created in Admin, User notification by email

Hobby developer, new with Python and Django.
Working on project which will include creating new users with a CustomUser(AbstractUser) Model via the Admin backend. On [Save] I want to auto-send email to the new user email [To:] and share the Username and Password provided when the new user was created by admin.
I'm using Python3.7 Django 2.2 on MacOS. Development being done in virtual env [Conda]. Email server setup in the development env as Backend File type. I have done 'extensive' search on forums [incl this one] ... tried the example code I could find. I have been able to send [then receive in Backend File] email on Form save but do not know how one would include the form variables in the email.
VIEWS.py
from django.shortcuts import render
from django.core.mail import send_mail
def notification_mail_send(request):
form = CustomUserCreationForm(request.POST)
if form.is_valid():
# SET UP MAIL CONTENT AND SEND MAIL
pass
FORMS.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'owner_fullname', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm):
model = CustomUser
fields = ('username', 'owner_fullname', 'email')
You should be able to access to form data with form.cleaned_data[field_name], where field_name would e.g. be "username".
If you are using a Django template to build your email content, pass the form object as context and use e.g. {{ form.cleaned_data.username }}
When using the django admin you don’t need to write your custom views and forms.
If you want to change the behavior of the admin you often need to overide the ModelAdmin class.
In your case I'd suggest to override save_model()
Thank to my fellow developers for assistance. I did deep dive into Rupin's suggestion and applied successfully using 'signals' : http://docs.djangoproject.com/en/2.2/topics/signals. Solved by merely adding 'if created': in the post_save_receiver(sender, instance, created, **kwargs): function in models.py.

Where do I create custom profile models for django-userena?

I have a django app called my_app that uses django-userena; I am trying to create and use my own profile model by following the django-userena installation documentation.
In my_app/models.py I've added
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile
class MyProfile(UserenaBaseProfile):
user = models.OneToOneField(User,
unique=True,
verbose_name=_('user'),
related_name='my_profile')
favourite_snack = models.CharField(_('favourite snack'),
max_length=5)
And then I've modified my_app/settings.py to include AUTH_PROFILE_MODULE = 'my_app.MyProfile' .
And yet, when I try to view any web page from my_app I get a SiteProfileNotAvailable. This error goes away if I move MyProfile to accounts/models.py
It seems like a bad idea to modify the accounts app in order to add custom fields. Am I wrong? Is there a way to add a custom profile module without modifying accounts/models.py?
I had the same issue. For me it happened because I forgot to put my_app (or accounts as in the official docs) into INSTALLED_APPS.

How to add a Model (not an app) to django?

I am using django 1.3 and just trying to add a simple model(not an app) to the admin site.
so i have tried:
from django.db import models
class UserProfile(models.Model):
notes = models.TextField(db_name="Notes", max_length=15)
def _str_(self):
return self.notes
class Admin:
pass
and have also tried creating the admin.py file in the site root and in the /static/admin/ directory and have attempted two standard entries for it as follows:
from django.contrib import admin
from mock.models import UserProfile
admin.site.register(UserProfile)
and
from django.contrib import admin
from mock.models import UserProfile
class UserProfileAdmin(admin.ModelAdmin):
pass
admin.site.register(UserProfile, UserProfileAdmin)
any help would be much appreciated. Thank you very much.
Don't define your Admin class in the model itself like below. That's the really old way to do it, from before Django 1.0. I'm not sure what tutorial or documentation you are using, but it's very out of date.
class UserProfile(models.Model):
notes = models.TextField(db_name="Notes", max_length=15)
# don't do this!
class Admin:
pass
Defining a UserProfileAdmin is the correct approach. The admin.py file should not go in the /static/admin/. The static directory is for static files like CSS stylesheets and javascript files, not for Django code.
As for your question of whether you can define a model without defining an app, it's not a really good idea. Lots of parts of django assume that each model belongs to an app. For example the database table name is appname_modelname.
Creating an app doesn't take too long. Run the startapp command and it will create the base directory and files.
./manage.py startapp <appname>
All you then need to do is add the new app to INSTALLED_APPS, and create your admin.py file.
As your project gets bigger, keeping models in apps will keep it more organized. Many Django users create an app named utils (or similar) for the odd model.

Categories