Django Admin: Creating users in the browser - python

I have setup my Django (1.8) admin to allow superusers to create new users interactively. My User model is customized using AbstractUser which means my admin file looks like this:
admin.py
from django.contrib import admin
from app.models import CPRUser
class UserAdmin(admin.ModelAdmin):
model = CPRUser
extra = 1
admin.site.register(CPRUser, UserAdmin)
and here is the model:
class CPRUser(AbstractUser):
student = models.PositiveIntegerField(verbose_name=_("student"),
default=0,
blank=True)
saved = models.IntegerField(default=0)
This appears to work OK, I can go through the admin and set the password, username and all the other custom fields of a new user. However, when I try and login with the newly created user, some part of the authentication process fails. I login from a page which is using the auth_views.login view and the boilerplate django login template.
On the other hand, if I create a new user using either manage.py createsuperuser or createuser() within the django shell, these users can login fine. This leads me to suspect it is to do with password storage or hashing - currently in the admin I can just type in a new user's password. Thing is, that is what I want to be able to do. How can I get this desired result - I want non-IT savy managers (whose details I won't have) to be able to easily create new users in the admin. I am aware of the risks of such a system.
The docs seem contradictory on setting this interactive user creation up in one section:
"The “Add user” admin page is different than standard admin pages in that it requires you to choose a username and password before allowing you to edit the rest of the user’s fields."
and then a couple of paragraphs later:
"User passwords are not displayed in the admin (nor stored in the database)"
Here is a screen shot of my admin:
How can I make Django accept the login attempts of users created interactively via the admin?

This is described in the documentation,
If your custom User model extends django.contrib.auth.models.AbstractUser, you can use Django’s existing django.contrib.auth.admin.UserAdmin class.
So, extending UserAdmin should do the trick.

Related

user login changes automatically in django

whenever I login in my admin panel, automatically my user site login changes to admin in django
I am using django's AuthenticationForm
from django.contrib.auth.forms import AuthenticationForm
this is my login form code
class LoginForm(AuthenticationForm):
username = UsernameField(widget=forms.TextInput(attrs={'autofocus':True, 'class':'form-control'}))
password = forms.CharField(label=_("Password"), strip=False ,widget=forms.PasswordInput(attrs={'autocomplete':'current-password', 'class':'form-control'}))
Yes, that's what is supposed to happen in Django. Whether you log in using the admin site or your own LoginForm, it's the same. The admin is just an app that only some users can use. In fact, you can log in as a user that has admin privileges (such as the superuser) using your regular LoginForm, and then you'll see that when you go to the admin, it will open automatically without logging in, because you already have logged in.
However, you can login to the admin on one window, and then open up a private window, and each one of those can be a different login. And if you need to test multiple users at the same time you can try Ghostery Browser, an extension for Firefox, or Ghost Browser, and there are others, specifically made so you can test multiple users without having to constantly log in an out.

Access Django DB objects without shell?

I have a request - can you help me access and manage django DB objects without using shell ?
I have created my models, but now (for example) i want to make a login system. I store users and passes(again, only an example), and i want to get the info from the DB, but i dont want to use shell.
What can i do in this case, im quite new to Django ?!
Best Regards
Why not use django-admin?
Maybe this is what you want:https://docs.djangoproject.com/en/3.0/ref/contrib/admin/
In views.py you can import
from .models import modelname
data = modelname.objects.all() - using this you can get all the data from the Database
Eg:-
for d in data:
print (d.email)
Will give all emails in the database
You can also use
t = modelname.objects.get(email='name#lk.com')
By this you can get the data of the person who's email is name#lk.com
Django already has database support where you can register your models and access them with a graphical interface.
See the documentation: django-admin-site
First you need to create a super user account, if you don't have one, create it with the terminal in the project directory, use this row:
python manage.py createsuperuser
For your model to appear on the admin site you need to register it
# models.py
class MyModel(models.Model)
field1 = models.CharField()
field2 = models.TextField()
# ...
# admin.py
from django.contrib import admin
from .models import MyModel
admin.site.register(MyModel)
So it's the basic way to register your model, if you want to personalize you need to check the documentation ModelAdmin.fieldsets
with this done, just access the admin site at the link http://localhost:8000/admin/ and log in with the super user account and you will see the model registered.

simple way to add existing users database(non django) to django

O.K. I have a headache with this problem. I have to different sites(non django) with login option and I would like to join in it into one new website based on django.
Each of these two user databases consist of table with columns:(username, password, e-mail).
The problem is, I just can not copy it to User table in Django as we all know django is very rigid about it, so I am trying to think a way, existing users would be able to login to site as nothing has changed.
Is there any django/pythonic way to do so?
I was thinking to create an app, which would take a foreign key to User model. Within User model I would create two users (database_1, database_2), so whenever a user from database 1 would login, e.g. JohnSmith, he would be connected as database_1 user, but so would JessicaSimpson if she would be in database 1. I am just thing to create Authentication and Authorization app as system app in some way... Is this a right way thinking? Would love to hear from professionals. Thanks
in models:
from django.db import models
from django.contrib.auth.models import User, Group
# Create your models here.
class New_users(models.Model):
new_user_id = models.ForeignKey(User, unique=False)
username = models.CharField(max_length=25)
password = models.CharField(max_length=25)
email = models.CharField(max_length=25)
in views:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
if request.method == 'POST':
#if username and password from New_users are ok...
login()#User where id is the same blah blah....
I'm a professional, and I would add the old users to the new DB and put in random passwords. I would also make a table of old_users with their old hashed passwords.
I would flag these old users such that, when they visit the new app, they would be forced to enter their old pw (you'd need to know the hash method) and, if successful, then set the old pw to the new user, and log them in.
If that's too much trouble, you could write a script that sends all the old users an email (naturally, you have their email address) and a link to a change_password form. It's pretty easy to extend the django reset password functionality. And it's a good thing to have.
Could you just migrate the existing users into the new database by looping through the existing users and calling the create_user function? This would take care of the password hashing and everything, assuming that you can decrypt your current passwords back to plaintext.

How to set/edit password in django admin view?

I have two models (Customer & Driver) which subclass the built in User class from Django. I have added these two models to Django Admin. In my current implementation, I allow password field to be set and edited from the admin. The admin stores the password in plain text - which is both insecure and incompatible with django's auth system. So the customers and drivers can't login using the password we set.
I need this password field look like:
I need a way to store the password like django does. Where and how should I do that?
admin.py
from django.contrib.auth.admin import UserAdmin
admin.site.register(User, UserAdmin) # User is Auth_User_Model
I don't know what you're doing but I'm pretty sure that you haven't used set_password() function.
The User class already has the capability of storing hashed passwords.
If you use it, the passwords will be stored like this:
You can even change the hashes used by Django by modifying the settings.py file. By default it uses PBKDF2PasswordHasher which is quite decent.
But if you want more security, you can use BCryptSHA256PasswordHasher
My settings.py file looks like this for all my current projects:
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
)
For more info, please read the documentation: https://docs.djangoproject.com/en/1.8/topics/auth/passwords/
Hope this helps.

Overriding admin views - Django

I am using Django 1.3 and python 2.7 .I am using Django admin app.What I want is when a superuser logs-in it should be shown admin/index.html with all models which is default behaviour but if any other user logs-in that is not superuser then it should be shown a totally different template with my data (like 'abc.html').What should I do to accomplish this?I guess I need to override some admin view to do this but have no idea?
Please help.If you want more information plz comment :)
I would create a middleware that checks if the user is a superuser or not. If the user is not supeuser you redirects him/her to the custom admin page instead of the default one.
class SuperUserMiddleware(object):
def process_request(self, request):
user = request.session.user
if not user.is_superuser:
return HttpResponseRedirect(NON_SUPERUSER_URL)
...
You create a modified AdminSite class definition with additional permission rules.
class SuperUserAdminSite( AdminSite ):
def has_permission(self, request):
return request.user.is_active and request.user.is_staff and request.user. is_superuser
Now you can create two AdminSite objects, one for ordinary users, one for super users.
You can have two paths in your URLs for the two admin sites.
Superusers can use both paths.
Ordinary users will only be able to use the ordinary user path in the URL.
https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#adminsite-objects
You have to change the view of the admin site. Django Documentation mention all in detail. Please check that https://docs.djangoproject.com/en/1.3/ref/contrib/admin/ if you have any error then please write back with some code details.

Categories

Resources