11👍
Just use self.request
like this:
from django.contrib import messages
messages.add_message(self.request, messages.INFO, 'Hello world.')
5👍
Using Django 2.2, and per the documentation here here is what worked for myself on a CLASS based view:
settings.py
INSTALLED_APPS = [
'django.contrib.messages',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
TEMPLATES = [
{
'BACKEND': #,
'DIRS': #,
'APP_DIRS': #,
'OPTIONS': {
'context_processors': [
'django.contrib.messages.context_processors.messages',
],
},
]
“The default storage backend relies on sessions. That’s why SessionMiddleware must be enabled and appear before MessageMiddleware in MIDDLEWARE.“
views.py
from django.contrib.messages.views import SuccessMessageMixin
class SignUpView(SuccessMessageMixin, CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('users:login')
template_name = 'users/register.html'
success_message = "%(username)s was created successfully"
urls.py
path(_('register/'), views.SignUpView.as_view(), name='register'),
And in the template:
(using bootstrap classes)
{% if messages %}
{% for message in messages %}
<div class="text-center alert alert-{{ message.tags }}">
{{ message|safe }}
</div>
{% endfor %}
{% endif %}
4👍
#Using django 3.2
#In views.py
from django.contrib import messages
from .models import CreateEmployer
from django.views.generic import CreateView
class SignUpView(CreateView):
model = CreateEmployer
template_name = ‘employee/register_employee.html’
fields = '__all__'
# this method will enable your message to display
# you can also use it to overwrite form data.
def form_valid(self, form):
messages.success(self.request, f”Account created successfully”)
return super().form_valid(form)
#in your urls.py
from .views import SingUpView
from django.urls import path
urlpatterns = [
path(‘register/‘, SignUpView.as_view(), name=“user-register"),
]
#in your template
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{message.tags}}">
{{message}}
</div>
{% endfor %}
{% endif %}
#I hope this helps anyone facing same problem in the future.
- Custom label on ModelChoiceField form field
- Django and Folium integration
- Is it possible to stop Django from creating .pyc files, whilst in development?
- Django REST Framework different depth for POST/PUT?
1👍
Django==3.2.8
views.py
Your CreateEmployee class inside views.py file you need to add this :-
def form_valid(self):
messages.success(self.request, f"Account created successfully")
return HttpResponseRedirect(self.get_success_url()
And
base.html
In top base.html you need to add this :-
<div class="container">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message|safe }}
</div>
{% endfor %}
{% endif %}
{% block content %}{% endblock content %}
</div>
Inside base.html class use bootstrap class.
- Django + uwsgi + nginx + SSL
- Unsupported lookup 'istartwith' for CharField or join on the field not permitted
- Django email
0👍
you have to set the message storage in settings.py
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
Greetings
- How to pass the remote IP to a proxied service? – Nginx
- Adding static() to urlpatterns only work by appending to the list
- Django admin, filter objects for inline formset
- Translating formatted strings in Django not working
0👍
You can also define MESSAGE_TAGS in your ‘settings.py’ for later use.
# settings.py
from django.contrib import messages
# Django messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-secondary',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
# views.py
from django.views.generic import ListView, CreateView, UpdateView, TemplateView
from django.contrib.messages.views import SuccessMessageMixin
class CreateEmployee(SuccessMessageMixin, CreateView):
model = Employee
template_name = 'employees/create.html'
form_class = frmCreate
success_message = 'Employee successful created'
def get_success_url(self):
return reverse('Employees:Create')
def get_context_data(self, **kwargs):
contexto = super(CreateEmployee, self).get_context_data(**kwargs)
contexto['action'] = reverse('Employees:Create')
return contexto
# and use in your template 'employees/create.html'
{% if messages %}
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible fade show" role="alert"
{{ message|striptags|safe }}
<button type="button" class="btn btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}
- Installed pytest but running `pytest` in bash returns `not found`
- Raising ValidationError from django model's save method?
- Ignore a specific test using Django
Source:stackexchange.com