I tried to display the message in django admin by using print method, but do not display the message.
Can you help me to display the message in Django admin by using condition?
Show messages in django
messages.debug(request, '%s SQL statements were executed.' % count)
messages.info(request, 'Three credits remain in your account.')
messages.success(request, 'Profile details updated.')
messages.warning(request, 'Your account expires in three days.')
messages.error(request, 'Document deleted.')
You need to study django message docs
Related
Ive been struggling with this problem for days now. As you se the validation error works but i want the error to show in the form and not redirect the user to the ValidationError page. What am i missing? I use django Alluth
def custom_signup(self, request, user):
user.profile.pid = self.cleaned_data[_("pid")]
data = User.objects.filter(profile__pid=user.profile.pid)
if data.exists():
raise forms.ValidationError(
_('This user exists in our system. Please try another.'),
code='unique_pid'
)
else:
user.save()
return user
Ok, so first you need to create a custom signup form, I've detailed how that is done in answer to this question
What you're seeing there is a 500 page, in debug mode (so you get all the information about what's happened). The reason that you're seeing this is that you are raising an error.
What you want to do, is to add an error to a form as part of that form's validation.
Once you've created your custom signup form, you can add your validation as part of the form's clean method;
def clean(self):
"""
Clean the form
"""
cleaned_data = super().clean()
pid = self.cleaned_data["pid"]
if User.objects.filter(profile__pid=pid).exists():
self.add_error(
'pid',
_('This user exists in our system. Please try another.'),
)
return cleaned_data
Please note, you're also using translation (_("")) to access the form's cleaned_data - you don't need to do this.
A client requires the ability for managers to add users to a company (with a random one time password) where the user must change their password before accessing anything. I am developing the app in Django 2.2
I made a custom user, replacing username with an email address and I added a change_password bool flag to the user. My change_password form/function works properly, but redirecting does not.
urls.py
path('change-password/', views.change_password, name='change-password'),
views.py
class Login(LoginView):
def form_valid(self, form):
# form is valid (= correct password), now check if user requires to set own password
if form.get_user().change_password:
return HttpResponseRedirect(reverse('change-password'))
else:
auth_login(self.request, form.get_user())
return HttpResponseRedirect(self.get_success_url())
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
request.user.change_password = False
request.user.save()
update_session_auth_hash(request, request.user)
return redirect(reverse('user_view'))
else:
return redirect(reverse('change-password'))
else:
form = PasswordChangeForm(user=request.user)
args = {'form': form}
return render(request, 'users/change_password.html', args)
The expected behavior is to redirect to change-password if the change_password flag is True, however, while the app does redirect to change-password, upon Submission the following error is thrown:
NotImplementedError: Django doesn't provide a DB representation for AnonymousUser.
If I add the decorator #login_required to my change_password function this error goes away, however, I am redirected back to the login page with the URL: users/login/?next=/users/change-password/
The problem is that in form_valid method you are calling form.get_user() which authenticates/gets the user and checks for the change_password correctly, but it does not log the user in, meaning that the user making the requests is still anonymous to the system. So while the user gets redirected they are not authenticated, which means that the request.user objects is of type AnonymousUser which does not live in the database hence the Django doesn't provide a DB representation for AnonymousUser error.
And when you use the #login_required decorator the user gets redirected to the login page because it is not a logged in user and the decorator requires the user to be logged in to see the view it is decorating.
The URL that you see users/login/?next=/users/change-password/ is basically how the login_required decorator works and it is doing two things:
1. redirect anonymous user to the login page (the users/login part of the URL)
2. once they have successfully logged in redirect them back from where they came from (?next=/users/change-password/)
My suggestion is that you pass the username of the user that tried to log in but has to change their password to the change_password view and have a form waiting for the user there that asks for the current password, new one and a confirmation of the new password. It is the simplest way to do what you want to do, but you will have to confirm that the users current password is correct again though.
Sorry for the confusing first answer, I didn't read the question right the first time, hopefully this makes more sense :)
I have created an app that allows users to create online products - basically a structured form fill with permissions. I'm using Django's basic auth for sign up and login. When a user signs up I want the account to be approved by an admin before they can log in. I know there are modules I can use to do this, but I wondered if there is something I can do to enable this without installing more stuff.
Here's the signup view:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
If it's not that simple and the best way is to use a module, which one is the best? I've seen a couple but am not sure which one to use, if I have to use one.
If you don't want to install third party module, I think you should extend Django's user model.
This is an official Django documentation about this subject.
https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#extending-the-existing-user-model
Design to record approve status on extended models. When the user logs in, it is likely that the approval status of the extended model is checked together with the Django login result, and the user is allowed to log in or not.
If you want to be notified about new users, you might want to use Django's "post_save" signal feature.
https://docs.djangoproject.com/en/1.11/ref/signals/
When you save something via django admin you will get this bootstrap alert bar at the top of your page saying "save" or "please correct errors". How do I pass something in get/post parameters to be displayed in such bar?
You're looking for Django's Messaging Framework.
Here's some code from the docs:
from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')
# Shortcut methods
messages.debug(request, '%s SQL statements were executed.' % count)
messages.info(request, 'Three credits remain in your account.')
messages.success(request, 'Profile details updated.')
messages.warning(request, 'Your account expires in three days.')
messages.error(request, 'Document deleted.')
I'm currently using SESSION_COOKIE_AGE = 60*60 to expire a Django session in 1 hour. I need to give a message to the user saying their session has expired on the login page.
Is there a way to test if the session has been expired? Or is there a message api for expired sessions in Django?
I poked around and didn't see anything for setting an expired session message.
Thanks!
To display the message that session is expired you can check if session exists in your logout view and change the success message accordingly
class Logout(View):
def get(self, request):
if request.session:
messages.success(request, 'Successfully Logged Out')
else:
messages.error(request, 'Session Expired Please Login Again')
logout(request)
return redirect(reverse('login'))
The warning typically provided to a user is an invitation to login :-).
What you could do is check SESSION_COOKIE_AGE (which provides the age of the cookie in seconds) and, if the user's session is about to expire, provide a warning to that effect.
I encouraged same problem and solved shown as below:
Django redirecting to LOGIN_URL after session expired.
So I pointed login url to logout view in settings.py for show message to user
and redirect to our login view.
settings.py:
LOGIN_URL = reverse_lazy('account:logout')
views.py:
class LogoutView(RedirectView):
url = reverse_lazy('account:login') # Our login view
def get(self, request, **kwargs):
# If session expired django clean request.session object.
# If user came to this view by clicking to logout button request.session not comes empty
if request.session.is_empty():
messages.error(request, "Your session has expired. Please login again to continue checking out.")
logout(request)
if request.GET.get('next'):
self.url = '{}?next={}'.format(self.url, request.GET.get('next'))
return super(LogoutView, self).get(request, **kwargs)