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)
Related
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
I am trying to make custom form for a model in the django admin area with a select field that is created on submit based on the request.user. The user would then pick from the select and it would save specific settings to the model.
the model:
class Thing1(models.Model):
user = models.ForeignKey(User)
setting_1 = models.BooleanField(default=False)
setting_2 = models.BooleanField(default=False)
setting_3 = models.BooleanField(default=False)
But instead of having the user set the settings fields manually, I'd like to display a Select with something like:
- Default Settings
- Other Settings
And the user would select one and the system would save the settings booleans accordingly. The actual options of the select depends on the user, so I need request.user to be able to build that select field. I don't seem to have access to request in the ModelForm.
So I know that I can exclude the settings fields from the model in django admin, but how do I get the form to include the select with the correct things in the select options for the user and then have it save the correct settings in the model on save?
I've read a bunch of other questions about custom django admin fields and got some ideas, but don't have a clear picture.
I have managed to add an additional field to the Registration form, "where did you hear about us?".
But I am not sure which files to edit in order to store the data from this field along with the users info.
i.e. When logging into the Admin section and go to "users" and view a users info I would like to see this field there.
Simplest way would be to store additional data in a UserProfile model about the user, e.g.
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
where_heard_about_us = models.TextField()
You can then register the object as an inline object in your Django Admin
I'm using the Django User model for my users. What I need is to add an action on the User admin that will enable me to send a text message to the users I'll have selected.
This is how it's supposed to work:
I log into Django admin
Select the Users model
Select a user from the list of users and then select the "Send Message" action I have created.
I should be redirected to another page that will have the selected user names, and fields from a "Text Message" model that I have created to handle text messages.
So far I've had to create another model:
class UserProfile(models.Model):
user = models.OneToOneField(User) #extended the User model
phone_number = models.CharField(u'Number', max_length=20)
and then the form for the Text Messages:
class TextMessageForm(ModelForm):
class Meta:
model = TextMessage
fields = ('sender', 'to', 'message')
but I'm having trouble adding an action to the User model(raises an "model already registered error" which I solved by unregistering but then the passwords in the User model are viscible. That's why I created the UserProfile model)
So, can I be able to add an action to the User model without having to mess with how it'll display stuff on the admin?
Can I have the action redirect to the text form(or another template for that matter)?
Or is this a bad way to think of it... I'm using this API to send my texts. Any direction you can offer?
You could extend the UserAdmin admin page:
# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
# Define a new User admin
class UserAdmin(UserAdmin):
"""My User Admin"""
# eg.
form = MyFancyForm
# or use my fancy template for the form
add_form_template = 'myadmin/user/add_form.html'
# or maybe add it to the change list
change_list_template = 'myadmin/user/change_list.html'
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#extending-the-existing-user-model
If you just want to add a button to go to another page to send a message, I'd modify the list template to add that button.
I am trying to create custom fields for users to enter on signup with django-allauth. I have referred to several posts about this, but I am not able to get my custom form to save to my database. I do get a combined form on my signup.html page with username, password1 and 2, email and my extra fields of city and school, but I am not able to save the extra fields to the database. I have run syncdb and can see my User Profile table in the admin area.
This advice is the closest I have come to the answer but I do not understand how to implement it: "You can't use UserProfileForm to the allauth.SIGNUP_FORM_CLASS. You need to extend it from SignUpForm and write a save method which will accept the newly created user as the only parameter," from this post:
Custom registration form for use with django-allauth
I have also attempted to integrate advice on this form these posts:
Django Allauth not saving custom form
How to customize user profile when using django-allauth
This is my code:
Models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
# A required line - links a UserProfile to User.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
school = models.CharField(max_length=128)
city = models.CharField(max_length=128)
def __unicode__(self):
return self.user.username
Forms.py
from django import forms
from django.contrib.auth.models import User
from myapp.models import UserProfile
from django.forms.widgets import HiddenInput
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('city', 'school')
def signup(self, request, user):
user=User.objects.get(email=request.email)
city=request.POST.get('city','')
school=request.POST.get('school','')
userprofile_obj = UserProfile(user=user,city=city,school=school)
userprofile_obj.save()
Settings.py
ACCOUNT_SIGNUP_FORM_CLASS = 'myapp.forms.UserProfileForm'
My template is the basic Signup.html from the django-allauth templates and I do not have a view made for this, although I attempted to make one from the tangowithdjango user authentication section register view, and this gave similar behavior (not saving to the database).
Thanks,
Kelly
Not sure if this is still an active question/issue for the original poster: if so, and for anyone else who comes across this, a few things to correct to at least move in the right direction:
I don't see an __init__() method that calls the superclass? E.g.:
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
use the user parameter to the signup method. It should be populated; don't reload it.
Ensure the two objects are linking correctly (I didn't use Django to build my profile table so YMMV but I set user.profile = Profile(...); then execute user.profile.save() at the end of my signup() method.
get the values to place into the profile from the form cleaned_data (e.g. self.cleaned_data['city'] not the POST.
Then start debugging: is your signup() method firing? What does it get? What happens when you execute the profile.save() method?