Here are the examples of the python api django.contrib.messages.ERROR taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
204 Examples
3
Source : admins.py
with Mozilla Public License 2.0
from Amsterdam
with Mozilla Public License 2.0
from Amsterdam
def freeze(self, request, queryset):
if not request.user.has_perm('questionnaires.change_session'):
messages.add_message(request, messages.ERROR, 'You have no permission to freeze Sessions')
return
total_count = queryset.count()
frozen_pre_count = queryset.filter(frozen=True).count()
if total_count == frozen_pre_count:
messages.add_message(request, messages.WARNING, 'All selected Session objects are already frozen')
return
queryset.exclude(frozen=True).update(frozen=True)
frozen_post_count = queryset.filter(frozen=True).count()
messages.add_message(request, messages.SUCCESS, f'{frozen_post_count-frozen_pre_count} Sessions frozen')
def unfreeze(self, request, queryset):
3
Source : admins.py
with Mozilla Public License 2.0
from Amsterdam
with Mozilla Public License 2.0
from Amsterdam
def unfreeze(self, request, queryset):
if not request.user.has_perm('questionnaires.change_session'):
messages.add_message(request, messages.ERROR, 'You have no permission to freeze Sessions')
return
total_count = queryset.count()
not_frozen_pre_count = queryset.filter(frozen=False).count()
if total_count == not_frozen_pre_count:
messages.add_message(request, messages.WARNING, 'All selected Session objects are already not frozen')
return
queryset.update(frozen=False)
unfrozen_post_count = queryset.filter(frozen=False).count()
messages.add_message(request, messages.SUCCESS, f'{unfrozen_post_count-not_frozen_pre_count} Sessions unfrozen')
3
Source : purchase_order.py
with GNU General Public License v3.0
from arrobalytics
with GNU General Public License v3.0
from arrobalytics
def delete(self, request, *args, **kwargs):
po_model: PurchaseOrderModel = self.get_object()
self.object = po_model
po_items_qs = po_model.itemthroughmodel_set.filter(bill_model__isnull=False)
if po_items_qs.exists():
messages.add_message(request,
message=f'Cannot delete {po_model.po_number} because it has related bills.',
level=messages.ERROR,
extra_tags='is-danger')
url = reverse('django_ledger:po-update',
kwargs={
'entity_slug': self.kwargs['entity_slug'],
'po_pk': self.kwargs['po_pk']
})
return HttpResponseRedirect(url)
success_url = self.get_success_url()
self.object.delete()
return HttpResponseRedirect(success_url)
3
Source : views.py
with MIT License
from cds-snc
with MIT License
from cds-snc
def render(self, form=None, **kwargs):
if not self.request.session.get("registrant_id"):
messages.add_message(
self.request,
messages.ERROR,
_("There has been an error, you need to confirm your email address"),
)
return redirect(reverse_lazy("register:registrant_email"))
return super().render(form, **kwargs)
def get_step_url(self, step):
3
Source : views.py
with MIT License
from cmu-lib
with MIT License
from cmu-lib
def create_archive(request):
"""
Creates a new journal archive containing the most up-to-date articles via the management command.
"""
try:
call_command('create_archive')
except:
messages.add_message(request, messages.ERROR, "Archive creation failed. Contact your system administrator.")
return redirect(reverse('archive_index'))
else:
messages.add_message(request, messages.SUCCESS, "New journal archive created")
return redirect(reverse('manage_issues'))
def browse_entries(request):
3
Source : account.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def login(request):
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
if user is not None:
auth_login(request, user)
return redirect(reverse("index"))
messages.add_message(request, messages.ERROR, "Could not login.")
return render(request, "account/login.html")
@transaction.atomic
3
Source : test_views.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def test_invalid_post(self, mock_tz):
# Can not unsubscribe from an activity you are not regitered to.
response = self.build_post_response({
'sign_up': False,
}, follow=True)
self.assertRedirects(response, self.base_url) # Should redirect to prevent resending the post on page refresh
self.assertTrue(ActivitySlot.objects.filter().exists())
self.assertHasMessage(response,
level=messages.ERROR,
text=ActivitySimpleMomentView.error_messages['not-registered'])
@patch('django.utils.timezone.now', side_effect=mock_now(datetime.datetime(2020, 8, 25, 0, 0)))
3
Source : test_views.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def test_invalid_post(self, mock_tz):
# Can not unsubscribe from an activity you are not registered to.
response = self.build_post_response({
'sign_up': True,
'slot_id': 8
}, follow=True)
self.assertRedirects(response, self.base_url) # Should redirect to prevent resending the post on page refresh
self.assertTrue(ActivitySlot.objects.filter().exists())
self.assertHasMessage(response,
level=messages.ERROR,
text=ActivityMomentWithSlotsView.error_messages['slot-full'])
# Tests in which cases a user can view private slot locations
def test_private_slot_locations(self):
3
Source : test_views.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def test_unsuccesfull_post(self, mock_tz):
# An empty response is bound to create some form of error in the form
response = self.build_post_response({
}, follow=False)
self.assertEqual(response.status_code, 200)
self.assertIn('form', response.context)
self.assertFalse(response.context['form'].is_valid())
self.assertHasMessage(response, level=messages.ERROR, text="correct your data")
@patch('django.utils.timezone.now', side_effect=mock_now())
3
Source : test_views.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def test_creation_none_denied(self, mock_tz):
Activity.objects.filter(id=2).update(slot_creation=Activity.SLOT_CREATION_STAFF)
response = self.client.get(self.base_url, follow=True)
self.assertEqual(response.status_code, 200)
self.assertRedirects(response, reverse('activity_calendar:activity_slots_on_day', kwargs={
'activity_id': 2,
'recurrence_id': datetime.datetime.fromisoformat('2020-08-12T14:00:00+00:00'),
}))
msg = str(_("You can not create slots on this activity.")) # add str() to run the proxy
self.assertHasMessage(response, level=messages.ERROR, text=msg)
@patch('django.utils.timezone.now', side_effect=mock_now())
3
Source : test_views.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def test_post_invalid_form(self):
# Get an item that causes the form to fail. This form should automatically forward when failing
# as the user can not adjust form data to fix it
response = self.client.post(self.get_base_url(ownership_id=2), data={}, follow=True)
self.assertRedirects(response, reverse('account:inventory:member_items'))
self.assertHasMessage(response, level=messages.ERROR)
class TestMemberItemLoanFormView(ViewValidityMixin, TestCase):
3
Source : test_views.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def test_post_invalid_form(self):
# Get an item that causes the form to fail. This form should automatically forward when failing
# as the user can not adjust form data to fix it
response = self.client.post(self.get_base_url(ownership_id=1), data={}, follow=True)
self.assertRedirects(response, reverse('account:inventory:member_items'))
self.assertHasMessage(response, level=messages.ERROR)
class TestMemberOwnershipAlterView(ViewValidityMixin, TestCase):
3
Source : test_views.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def test_post_unsuccesful(self):
response = self.client.post(self.get_base_url(ownership_id=1), data={}, follow=True)
success_url = reverse('inventory:catalogue_item_links', kwargs={'type_id': self.content_type, 'item_id': 1})
self.assertRedirects(response, success_url)
self.assertHasMessage(response, level=messages.ERROR, text="This action was not possible")
def test_deactivation_post(self):
3
Source : test_views.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def test_post_unsuccessful(self):
""" Tests a succesful post """
response = self.client.post(self.get_base_url(ownership_id=1), data={}, follow=True)
faillure_url = reverse('inventory:catalogue_item_links', kwargs={'type_id': self.content_type, 'item_id': self.item.id})
self.assertRedirects(response, faillure_url)
self.assertHasMessage(response, level=messages.ERROR, text="This action was not possible")
3
Source : view_curves.py
with MIT License
from fga-eps-mds
with MIT License
from fga-eps-mds
def post(self, request, *args, **kwargs):
try:
with transaction.atomic():
data = super().post(request, *args, **kwargs)
return data
except IntegrityError:
messages.add_message(request, messages.ERROR,
_('The patient already has a curve at this '
'age. If wanted, just change its data.'))
return render(request, template_name=self.template_name,
context=self.get_context_data())
class CurvesUpdateView(
3
Source : admin_mixin.py
with GNU General Public License v3.0
from gojuukaze
with GNU General Public License v3.0
from gojuukaze
def response_delete(self, request, obj_display, obj_id):
response = super().response_delete(request, obj_display, obj_id)
if request._messages:
other = []
error = []
for m in request._messages:
if m.level == messages.ERROR:
error.append(m)
else:
other.append(m)
request._messages._queued_messages = error or other
return response
3
Source : admin.py
with MIT License
from HackSoftware
with MIT License
from HackSoftware
def save_model(self, request, obj, form, change):
if change:
return super().save_model(request, obj, form, change)
try:
user_create(**form.cleaned_data)
except ValidationError as exc:
self.message_user(request, str(exc), messages.ERROR)
3
Source : views.py
with Apache License 2.0
from hutomadotAI
with Apache License 2.0
from hutomadotAI
def post(self, request, aiid, *args, **kwargs):
"""We use forms to secure POST requests"""
form = ProxyRegenerateWebhookSecretForm(request.POST)
if form.is_valid():
return JsonResponse(post_regenerate_webhook_secret(
self.request.session.get('token', False),
aiid
))
else:
level = messages.ERROR
message = 'Something went wrong'
messages.add_message(self.request, level, message)
return redirect('studio:summary')
class ProxyAiView(View):
3
Source : views.py
with Apache License 2.0
from hutomadotAI
with Apache License 2.0
from hutomadotAI
def form_invalid(self, form):
"""Add error message and go back to where you've came from"""
messages.add_message(self.request, messages.ERROR, form.errors.as_text())
return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))
def form_valid(self, form):
3
Source : models.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def serve(self, request, *args, **kwargs):
try:
return super().serve(request, *args, **kwargs)
except EmailException as Ex:
messages.add_message(
request, messages.ERROR, message="Failed to send email"
)
raise EmailException
FormPage.content_panels = [
3
Source : admin.py
with MIT License
from imankarimi
with MIT License
from imankarimi
def changelist_view(self, request, extra_context=None):
filename = request.GET.get('file_name', settings.LOG_READER_DEFAULT_FILE)
is_valid, file_contents = read_file_lines(file_name=filename)
if not is_valid:
self.message_user(request, file_contents, level=messages.ERROR)
log_files = get_log_files(settings.LOG_READER_DIR_PATH)
context = dict(
self.admin_site.each_context(request),
log_files=log_files,
file_contents=file_contents if is_valid else [],
file_name=filename,
django_version=django.get_version()
)
return TemplateResponse(request, "log_reader/admin/change_list.html", context=context)
3
Source : views.py
with GNU General Public License v3.0
from kiwitcms
with GNU General Public License v3.0
from kiwitcms
def check_owner(request):
# super-user can edit all tenants
if request.user.is_superuser:
return None
# tenant owner can edit their own tenant
if request.user == request.tenant.owner:
return None
messages.add_message(
request,
messages.ERROR,
_("Only super-user and tenant owner are allowed to edit tenant properties"),
)
return HttpResponseRedirect('/')
def get(self, request, *args, **kwargs):
3
Source : views.py
with GNU General Public License v3.0
from kiwitcms
with GNU General Public License v3.0
from kiwitcms
def get(self, request, *args, **kwargs):
if not utils.owns_tenant(request.user, request.tenant):
messages.add_message(
request,
messages.ERROR,
_("Only users who are authorized for this tenant can invite others"),
)
return HttpResponseRedirect('/')
return super().get(self, request, *args, **kwargs)
def form_valid(self, form):
3
Source : views.py
with GNU General Public License v2.0
from mango-wyc
with GNU General Public License v2.0
from mango-wyc
def sign_up(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if User.objects.filter(username=username).exists():
messages.add_message(request, messages.ERROR, '用户名已存在!')
else:
user_obj = User.objects.create_user(username=username, password=password)
UserProfile.objects.create(user=user_obj)
messages.add_message(request, messages.SUCCESS, '注册成功!')
return HttpResponseRedirect('/')
return render(request, 'sign_up.html')
def sign_in(request):
3
Source : model.py
with GNU Lesser General Public License v3.0
from opentaps
with GNU Lesser General Public License v3.0
from opentaps
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
try:
self.object.delete()
except ProtectedError:
messages.add_message(request, messages.ERROR, 'Can not delete: this Model is being used!')
return HttpResponseRedirect(self.object.get_absolute_url())
return HttpResponseRedirect(success_url)
model_delete_view = ModelDeleteView.as_view()
3
Source : tag.py
with GNU Lesser General Public License v3.0
from opentaps
with GNU Lesser General Public License v3.0
from opentaps
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
try:
self.object.delete()
except ProtectedError:
messages.add_message(request, messages.ERROR, 'Can not delete: this Tag is being used!')
return HttpResponseRedirect(self.object.get_absolute_url())
return HttpResponseRedirect(success_url)
tag_delete_view = TagDeleteView.as_view()
3
Source : transaction.py
with GNU Lesser General Public License v3.0
from opentaps
with GNU Lesser General Public License v3.0
from opentaps
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
try:
self.object.delete()
except ProtectedError:
messages.add_message(request, messages.ERROR, 'Can not delete this Transaction!')
return HttpResponseRedirect(self.object.get_absolute_url())
return HttpResponseRedirect(success_url)
transaction_delete_view = TransactionDeleteView.as_view()
3
Source : views.py
with GNU Lesser General Public License v3.0
from opentaps
with GNU Lesser General Public License v3.0
from opentaps
def form_valid(self, form):
if form.cleaned_data['use_async']:
self.object = form.save()
return HttpResponseRedirect(reverse("core:get_task_progress", kwargs={'task_id': self.object.task_id}))
else:
try:
return super().form_valid(form)
except Exception as e:
logger.exception(e)
messages.add_message(self.request, messages.ERROR, 'Can not create the model: {}'.format(e))
return super().form_invalid(form)
meter_model_create_view = MeterModelCreateView.as_view()
3
Source : views.py
with GNU Lesser General Public License v3.0
from opentaps
with GNU Lesser General Public License v3.0
from opentaps
def start_agent(request, platform, agent):
url = reverse('volttron:status')
client = VolttronClient()
try:
client.start_agent(platform, agent)
return HttpResponseRedirect(url)
except Exception as e:
logger.exception('start_agent error')
messages.add_message(request, messages.ERROR, str(e))
return HttpResponseRedirect(url)
@require_POST
3
Source : views.py
with GNU Lesser General Public License v3.0
from opentaps
with GNU Lesser General Public License v3.0
from opentaps
def stop_agent(request, platform, agent):
url = reverse('volttron:status')
client = VolttronClient()
try:
client.stop_agent(platform, agent)
return HttpResponseRedirect(url)
except Exception as e:
logger.exception('stop_agent error')
messages.add_message(request, messages.ERROR, str(e))
return HttpResponseRedirect(url)
@require_POST
3
Source : views.py
with GNU Lesser General Public License v3.0
from opentaps
with GNU Lesser General Public License v3.0
from opentaps
def delete_agent_config(request, platform, agent):
url = reverse('volttron:agent_view', kwargs={"platform": platform, "agent": agent})
client = VolttronClient()
agent_key = platform + agent
agent_dict = client.agent_uuid_dict.get(agent_key)
try:
if not agent_dict:
logger.warn('Volttron agent %s not found in platform %s', agent, platform)
client.list_platforms()
agent_dict = client.agent_uuid_dict.get(agent_key)
client.delete_agent_config(platform, agent_dict, request.POST.get('config_name'))
return HttpResponseRedirect(url)
except Exception as e:
logger.exception('delete_agent_config error')
messages.add_message(request, messages.ERROR, str(e))
return HttpResponseRedirect(url)
@require_POST
3
Source : admin_filters.py
with BSD 2-Clause "Simplified" License
from peppelinux
with BSD 2-Clause "Simplified" License
from peppelinux
def queryset(self, request, queryset):
"""?custom_search=filter,mail__exact,peppelinux%40yahoo.it||
"""
if request.GET.get(self.parameter_name):
post = dict(request.GET)[self.parameter_name][0]
search_list = []
search_list = post.split('||')
for se in search_list:
sple = se.split(',')
se_dict = {'{}__{}'.format(sple[0], sple[2]): sple[3]}
try:
queryset = getattr(queryset, sple[1])(**se_dict)
except Exception as e:
messages.add_message(request, messages.ERROR,
'Search filter {} failed: {}'.format(se, e))
return queryset
def choices(self, changelist):
3
Source : views.py
with MIT License
from PyAr
with MIT License
from PyAr
def handle_no_permission(self):
if self.get_permission_denied_message() == CANT_CHANGE_CLOSE_EVENT_MESSAGE:
messages.add_message(self.request, messages.ERROR, CANT_CHANGE_CLOSE_EVENT_MESSAGE)
return redirect('event_detail', pk=self.get_object().pk)
else:
return super(EventChangeView, self).handle_no_permission()
class BankOrganizerAccountDataUpdateView(PermissionRequiredMixin, generic.edit.UpdateView):
3
Source : views.py
with MIT License
from PyAr
with MIT License
from PyAr
def handle_no_permission(self):
if self.get_permission_denied_message() == MUST_BE_ACCOUNT_OWNER_MESSAGE:
messages.add_message(self.request, messages.ERROR, MUST_BE_ACCOUNT_OWNER_MESSAGE)
return redirect('organizer_detail', pk=self._get_organizer().pk)
if self.get_permission_denied_message() == MUST_BE_ORGANIZER_MESSAGE:
messages.add_message(self.request, messages.ERROR, MUST_BE_ORGANIZER_MESSAGE)
return redirect('events_home')
return super(BankOrganizerAccountDataUpdateView, self).handle_no_permission()
def get_success_url(self):
3
Source : views.py
with MIT License
from PyAr
with MIT License
from PyAr
def handle_no_permission(self):
if self.get_permission_denied_message() == MUST_BE_ORGANIZER_MESSAGE:
messages.add_message(self.request, messages.ERROR, MUST_BE_ORGANIZER_MESSAGE)
return redirect('events_home')
return super(BankOrganizerAccountDataCreateView, self).handle_no_permission()
def get_context_data(self, **kwargs):
3
Source : views.py
with MIT License
from PyAr
with MIT License
from PyAr
def post(self, request, *args, **kwargs):
try:
with transaction.atomic():
return super().post(request, *args, **kwargs)
except IntegrityError:
messages.add_message(request, messages.ERROR, DUPLICATED_SPONSOR_CATEGORY_MESSAGE)
return redirect('event_detail', pk=self._get_event().pk)
def has_permission(self):
3
Source : test_comments.py
with MIT License
from Radi85
with MIT License
from Radi85
def test_bad_signature(self):
key = self.key + 'invalid'
_url = self.get_url(key)
response = self.client.get(_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Comment.objects.all().count(), self.init_count)
self.template_used_test(response)
response_messages = response.context['messages']
self.assertEqual(len(response_messages), 1)
for r in response_messages:
self.assertEqual(r.level, messages.ERROR)
self.assertEqual(r.message, EmailError.BROKEN_VERIFICATION_LINK)
self.assertTextTranslated(r.message, _url)
def test_comment_exists(self):
3
Source : admin.py
with MIT License
from shinneider
with MIT License
from shinneider
def get_queryset(self, request):
"""
override django admin 'get_queryset'
"""
queryset = super().get_queryset(request)
try:
return queryset.filter(self.advanced_search_query(request))
except Exception: # pylint: disable=broad-except
messages.add_message(request, messages.ERROR, 'Filter not applied, error has occurred')
return queryset.none()
def changelist_view(self, request, extra_context=None):
3
Source : admin.py
with GNU Affero General Public License v3.0
from svthalia
with GNU Affero General Public License v3.0
from svthalia
def _show_message(
model_admin: ModelAdmin, request: HttpRequest, n: int, message: str, error: str
) -> None:
if n == 0:
model_admin.message_user(request, error, messages.ERROR)
else:
model_admin.message_user(
request,
message % {"count": n, "items": model_ngettext(model_admin.opts, n)},
messages.SUCCESS,
)
@admin.register(Payment)
3
Source : test_admin.py
with GNU Affero General Public License v3.0
from svthalia
with GNU Affero General Public License v3.0
from svthalia
def test_show_message(self, admin_mock) -> None:
admin_mock.return_value = admin_mock
request = Mock(spec=HttpRequest)
admin._show_message(admin_mock, request, 0, "message", "error")
admin_mock.message_user.assert_called_once_with(
request, "error", messages.ERROR
)
admin_mock.message_user.reset_mock()
admin._show_message(admin_mock, request, 1, "message", "error")
admin_mock.message_user.assert_called_once_with(
request, "message", messages.SUCCESS
)
@override_settings(SUSPEND_SIGNALS=True, THALIA_PAY_ENABLED_PAYMENT_METHOD=True)
3
Source : admin.py
with GNU Affero General Public License v3.0
from svthalia
with GNU Affero General Public License v3.0
from svthalia
def _show_message(model_admin, request, n, message, error):
"""Show a message in the Django Admin."""
if n == 0:
model_admin.message_user(request, error, messages.ERROR)
else:
model_admin.message_user(
request,
message % {"count": n, "items": model_ngettext(model_admin.opts, n)},
messages.SUCCESS,
)
@admin.register(Registration)
3
Source : test_admin.py
with GNU Affero General Public License v3.0
from svthalia
with GNU Affero General Public License v3.0
from svthalia
def test_show_message(self, admin_mock):
admin_mock.return_value = admin_mock
request = Mock(spec=HttpRequest)
admin._show_message(admin_mock, request, 0, "message", "error")
admin_mock.message_user.assert_called_once_with(
request, "error", messages.ERROR
)
admin_mock.message_user.reset_mock()
admin._show_message(admin_mock, request, 1, "message", "error")
admin_mock.message_user.assert_called_once_with(
request, "message", messages.SUCCESS
)
@override_settings(SUSPEND_SIGNALS=True)
3
Source : views.py
with GNU Affero General Public License v3.0
from Unicaronas
with GNU Affero General Public License v3.0
from Unicaronas
def get_redirect_url(self, *args, **kwargs):
request = self.request
code = self.request.GET.get('code', False)
state = self.request.GET.get('state', '')
if not code:
messages.add_message(request, messages.ERROR, 'Ocorreu um erro atualizando o token da página!')
return super().get_redirect_url(self, *args, **kwargs)
user = request.user
fb_group_id = request.session.get('fb_group_id', None)
fb_group = get_object_or_404(FacebookGroup, id=fb_group_id, user=user)
token = exchange_code(request, code, state)
fb_group.update_token(token)
messages.add_message(request, messages.SUCCESS, 'Token atualizado!')
del request.session['fb_group_id']
del request.session['fb_state']
return super().get_redirect_url(self, *args, **kwargs)
3
Source : views.py
with BSD 2-Clause "Simplified" License
from unicef
with BSD 2-Clause "Simplified" License
from unicef
def post(self, request):
form = NewMessageForm(data=request.POST)
if form.is_valid():
user = request.user
data = form.cleaned_data
thread = ChatManager.initiate_thread(
sender=user, recipients=[], chatbot=data['chatbot'], subject=data['subject'], text=data['text'])
return redirect(reverse('messaging:thread', kwargs={'thread_id': thread.pk}))
messages.add_message(request, messages.ERROR, 'Can\'t connect with bot.')
return redirect(request.META.get('HTTP_REFERER'))
@method_decorator(login_required, name='dispatch')
3
Source : admin.py
with Apache License 2.0
from UniversitaDellaCalabria
with Apache License 2.0
from UniversitaDellaCalabria
def save_model(self, request, obj, form, change):
try:
obj.validate()
super(ServiceProviderAdmin, self).save_model(
request, obj, form, change)
except Exception as e: # pragma: no cover
messages.set_level(request, messages.ERROR)
msg = "{}".format(e)
messages.add_message(request, messages.ERROR, msg)
3
Source : views.py
with MIT License
from vabene1111
with MIT License
from vabene1111
def account(request):
if not request.user.groups.filter(name='User').exists() and not request.user.is_superuser:
messages.add_message(request, messages.ERROR, _('You do not have the required permissions to perform this action!'))
return HttpResponseRedirect(reverse_lazy('index'))
token, created = Token.objects.get_or_create(user=request.user)
return render(request, 'user.html', {'token': token})
3
Source : base.py
with MIT License
from Xavier-Lam
with MIT License
from Xavier-Lam
def _clientaction(self, request, action, failed_msg, kwargs=None):
"""调用微信请求action"""
kwargs = kwargs or dict()
try:
msg = action()
self.message_user(request, msg)
except Exception as e:
kwargs.update(exc=e)
msg = failed_msg % kwargs
if isinstance(e, WeChatClientException):
request.app.logger("admin").warning(msg, exc_info=True)
else:
request.app.logger("admin").error(msg, exc_info=True)
self.message_user(request, msg, level=messages.ERROR)
#endregion
#region model
def get_queryset(self, request):
3
Source : mixins.py
with MIT License
from yezz123
with MIT License
from yezz123
def dispatch(self, request, uid, *args, **kwargs):
try:
setattr(
self,
re.sub(r"(? < !^)(?=[A-Z])", "_", self.model.__name__).lower(),
self.model.objects.get(uid=uid),
)
except (TypeError, ValueError, OverflowError, self.model.DoesNotExist):
messages.add_message(
request,
messages.ERROR,
f"The {self.model.__name__.lower()} doesn't exist.",
)
return HttpResponseRedirect("/")
return super().dispatch(request, *args, **kwargs)
class NextPageMixin:
3
Source : views.py
with MIT License
from yezz123
with MIT License
from yezz123
def get(self, request):
pdf = generate_pdf(self.invoice)
if not pdf:
messages.add_message(
request, messages.ERROR, "The invoice template is invalid."
)
return HttpResponseRedirect(reverse("invoices:list"))
response = HttpResponse(pdf, content_type="application/pdf")
response[
"Content-Disposition"
] = f'inline; filename="{self.invoice.invoice_id}.pdf"'
return response
class EditView(PermissionsRequiredMixin, AccessModelMixin, NextPageMixin, View):
3
Source : views.py
with MIT License
from yezz123
with MIT License
from yezz123
def get(self, request):
if self.invoice.status > 0:
messages.add_message(
request,
messages.ERROR,
"The invoice is not deletable anymore. If needed, mark it as obsolete",
)
return HttpResponseRedirect(self.next)
return render(request=request, template_name="invoices/delete.html")
def post(self, request):
See More Examples