我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.messages.ERROR。
def change_event(modeladmin, request, queryset): event_pk = request.POST['event'] try: event = Event.objects.get(pk=event_pk) except Event.DoesNotExist: modeladmin.message_user( request, "Could not find event with pk {event_pk}".format( event_pk=event_pk ), messages.ERROR, ) return queryset.update(event=event) modeladmin.message_user( request, "Added event {event} for {n} quotes".format( event=event.name, n=queryset.count(), ), messages.SUCCESS, )
def login_view(request): if request.POST: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) messages.add_message(request, messages.SUCCESS, "Login successful.", extra_tags='success') return redirect('account:home') else: messages.add_message(request, messages.ERROR, "You account is disabled.", extra_tags='danger') return redirect('account:login') else: messages.add_message(request, messages.ERROR, "Your username and/or your password is incorrect.", extra_tags='warning') return redirect('account:login') else: if request.user.is_authenticated(): return redirect('account:home') else: return render(request, 'autostew_web_account/login.html')
def post(self, request, *args, **kwargs): if not request.user.has_perm('file.manage_resources'): raise PermissionDenied parent = self._get_folder() form = ResourceFolderForm(folder=parent, data=self.request.POST) folder = ResourceFolder.objects.filter(parent=parent, name=form.data['name']).first() if folder is not None: messages.add_message(request, messages.ERROR, 'Un dossier existe déjà avec ce nom') else: folder = ResourceFolder.objects.create( name=form.data['name'], parent=parent ) messages.add_message(request, messages.SUCCESS, 'Dossier créé') return redirect(reverse('resource-folder-list', kwargs={'folder_pk': folder.id}))
def post(self, request, *args, **kwargs): if 'resign' in request.POST: club = Club.objects.get(id=request.POST['club_id']) if club.remove_member(request.user, request.user): messages.add_message(request, messages.SUCCESS, 'Successfully resigned from %s.' % club.club_name) else: messages.add_message(request, messages.ERROR, 'Could not resign from %s.' % club.club_name) elif 'disband' in request.POST: club = Club.objects.get(id=request.POST['club_id']) club._clear_permissions() club.delete() messages.add_message(request, messages.SUCCESS, 'Sucessfully disbanded %s.' % club.club_name) clubs = request.user.get_clubs() return render(request, self.template_name, {'clubs' : clubs})
def post(self, request, club_id, *args, **kwargs): club = Club.objects.get(pk=club_id) old_club_name = club.club_name form = self.form_class(instance=club) if 'edit' in request.POST: form = self.form_class(request.POST, request.FILES, instance=club) if form.is_valid(): club.update_group_names(old_club_name) club = form.save() return HttpResponseRedirect(reverse('suite:club_manage')) else: messages.add_message(request, messages.ERROR, 'Could not make changes to your club.') return render(request, self.template_name, { 'form' : form, 'club' : club })
def post(self, request, club_id, event_id, *args, **kwargs): club = suite.models.Club.objects.get(pk=club_id) event = suite.models.Event.objects.get(pk=event_id) form = self.form_class(instance=event) if 'edit' in request.POST: form = self.form_class(request.POST, request.FILES, instance=event) if form.is_valid(): event = form.save() #print('valid') messages.add_message(request, messages.SUCCESS, 'Successfully edited event.') return HttpResponseRedirect(reverse('suite:club_view', kwargs={'club_id': club.id })) else: messages.add_message(request, messages.ERROR, 'Could not make changes to your event.') return render(request, self.template_name, { 'form' : form, 'club' : club, 'event' : event})
def post(self, request, club_id, *args, **kwargs): club = get_object_or_404(Club, pk=club_id) if 'delete' in request.POST: user_id = request.POST['delete'] if not club.remove_member(request.user, User.objects.get(id=user_id)): messages.add_message(request, messages.ERROR, 'Cannot delete Yourself!') elif 'promote' in request.POST: user_id = request.POST['promote'] act_on_user = User.objects.get(id=user_id) if not club.is_officer(act_on_user): club.promote_to_officer(request.user, act_on_user) elif club.is_officer(act_on_user): club.promote_officer_to_owner(request.user, act_on_user) elif 'demote' in request.POST: user_id = request.POST['demote'] act_on_user = User.objects.get(id=user_id) if club.is_owner(act_on_user): if not club.demote_owner_to_officer(request.user, act_on_user): messages.add_message(request, messages.ERROR, 'You Cannot Demote Yourself!') elif club.is_officer(act_on_user): club.demote_from_officer(request.user, act_on_user) members = self.get_members(club) return render(request, self.template_name, {'club': club, 'members' : members})
def post(self, request): if 'details' in request.POST: form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() else: messages.add_message(request, messages.ERROR, 'Could not edit account details.') form2 = PasswordChangeForm(user=request.user) args = {'form': form, 'form2': form2 } return render(request, 'account.html', args) elif 'password' in request.POST: form2 = PasswordChangeForm(user=request.user, data=request.POST) if form2.is_valid(): form2.save() update_session_auth_hash(request, form2.user) messages.add_message(request, messages.SUCCESS, 'Sucessfully changed password.') else: messages.add_message(request, messages.ERROR, 'Password change unsuccessful.') form = EditProfileForm(instance=request.user) args = {'form': form, 'form2': form2 } return render(request, 'account.html', args)
def start_instances(self, request, queryset): """ Start all transmitted PostgreSQL instances Skip already running services. """ for inst in queryset: if inst.is_online: self.message_user(request, "%s is already running." % inst, messages.WARNING ) continue try: util = PGUtility(inst) util.start() except Exception, e: self.message_user(request, "%s : %s" % (e, inst), messages.ERROR) continue self.message_user(request, "%s started!" % inst)
def stop_instances(self, request, queryset): """ Stop all transmitted PostgreSQL instances Skip already stopped services. """ for inst in queryset: if not inst.is_online: self.message_user(request, "%s is already stopped." % inst, messages.WARNING ) continue try: util = PGUtility(inst) util.stop() except Exception, e: self.message_user(request, "%s : %s" % (e, inst), messages.ERROR) continue self.message_user(request, "%s stopped!" % inst)
def restart_instances(self, request, queryset): """ Restart all transmitted PostgreSQL instances Basicaly we just call for a fast stop followed by a start. Nothing complicated here. Unlike stop, we don't skip stopped instances, and unline start, we don't skip running ones. """ for inst in queryset: try: util = PGUtility(inst) util.stop() util.start() except Exception, e: self.message_user(request, "%s : %s" % (e, inst), messages.ERROR) continue self.message_user(request, "%s restarted!" % inst)
def reload_instances(self, request, queryset): """ Reload all transmitted PostgreSQL instances This is provided as a way of reloading configuration files. """ for inst in queryset: try: util = PGUtility(inst) util.reload() except Exception, e: self.message_user(request, "%s : %s" % (e, inst), messages.ERROR) continue self.message_user(request, "%s config files reloaded!" % inst)
def server_edit(request): msg = '' ftp_id = request.REQUEST.get('id', '') if request.method == 'POST': ftp_name = request.REQUEST.get('ftp_name', '') server_id = request.REQUEST.get('server_id', '') ftp_port = request.REQUEST.get('ftp_port', '') ftp_description = request.REQUEST.get('ftp_description', '') ovs = OpsFtpServer(request.user) res, msg = ovs.server_edit(ftp_id, ftp_name, server_id, ftp_port, ftp_description) if res: messages.add_message(request, messages.SUCCESS, 'FTP??????????????????????') return HttpResponseRedirect('/pureftp/s/list/') if ftp_id: data = FtpServer.objects.get(pk=ftp_id) server_list = Server.objects.all() return render_to_response('pureftp/s_edit.html', {'msg': msg, 'data': data, 'server_list': server_list}, context_instance=RequestContext(request)) else: messages.add_message(request, messages.ERROR, '???????????????????') return HttpResponseRedirect('/pureftp/s/list/')
def server_del(request): """ :param request: :return: """ vpn_id = request.REQUEST.get('id', '') if vpn_id: ftp_server_info = FtpServer.objects.get(pk=vpn_id) account_num = FtpAccount.objects.filter(ftp_server=ftp_server_info).count() if account_num < 1: msg = 'FTP????????' FtpServer.objects.get(pk=vpn_id).delete() messages.add_message(request, messages.SUCCESS, msg) else: msg = '?????FTP????ERROR: ??SERVER?????????????????????????IP?' messages.add_message(request, messages.ERROR, msg) else: msg = 'ID?????????' messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect("/pureftp/s/list/")
def group_edit(request): if request.method == 'POST': # form = GroupEditForm(request.POST) # if form.is_valid(): # cd = form.cleaned_data ops_server = OpsGroup(request.user) res, msg = ops_server.group_edit(request.POST) if res: messages.add_message(request, messages.SUCCESS, msg) else: messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect('/system/g/list/') else: gid = request.REQUEST.get('gid', '') data = Group.objects.get(pk=gid) group_perms = data.permissions.all() all_perms = Permission.objects.all() return render_to_response('system/group_edit.html', {'data': data, 'group_perms': group_perms, 'all_perms': all_perms})
def permit_add(request): """ ???? :param request: :return: """ if request.method == 'POST': ops_permit = OpsPermit(request.user) res, msg = ops_permit.permit_add(request.POST) page = int(request.REQUEST.get('page', 1)) if res: messages.add_message(request, messages.SUCCESS, msg) else: messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect('/system/p/list/?page=' + str(page)) else: content_type_list = ContentType.objects.all() return render_to_response('system/permit_add.html', {'content_type_list': content_type_list}, context_instance=RequestContext(request))
def addcard(request): if request.method == 'POST': token = request.POST['stripe_token[id]'] user_profile = UserProfile.objects.get(user=request.user) network = user_profile.network if network.update_card(token): messages.add_message(request, messages.INFO, "addcard_saved", extra_tags="billing_resp_code") return redirect("/dashboard/billing") else: # The card has been declined messages.add_message(request, messages.ERROR, "addcard_stripe_declined", extra_tags="billing_resp_code") return redirect("/dashboard/billing") else: return HttpResponseBadRequest()
def form_valid(self, form): #add the dates to the existing data in the sessions notice = form.save(commit=False) serializer = NoticeSerializer(notice) session_data = self.request.session['new-notice'] session_data['starts_at'] = serializer.data['starts_at'] session_data['ends_at'] = serializer.data['ends_at'] session_data['timezone'] = serializer.data['timezone'] #save serializer = NoticeSerializer(data=session_data) if serializer.is_valid(): notice = serializer.save(user=self.request.user) messages.add_message(self.request, messages.SUCCESS, 'Your notice has been posted') return redirect(notice) else: messages.add_message(self.request, messages.ERROR, 'Sorry, something went wrong')
def create_slack_channels(self, request, queryset): team_ids = [] skipped = 0 for team in queryset.select_related('season').nocache(): if not team.season.is_active or team.season.is_completed: self.message_user(request, 'The team season must be active and not completed in order to create channels.', messages.ERROR) return if len(team.season.tag) > 3: self.message_user(request, 'The team season tag is too long to create a channel.', messages.ERROR) return if team.slack_channel == '': team_ids.append(team.pk) else: skipped += 1 signals.do_create_team_channel.send(sender=self, team_ids=team_ids) self.message_user(request, 'Creating %d channels. %d skipped.' % (len(team_ids), skipped), messages.INFO) #-------------------------------------------------------------------------------
def approve(self, request, queryset): if not request.user.has_perm('tournament.invite_to_slack'): self.message_user(request, 'You don\'t have permissions to invite users to slack.', messages.ERROR) return redirect('admin:tournament_registration_changelist') count = 0 for reg in queryset: if reg.status == 'pending' and reg.validation_ok and not reg.validation_warning: workflow = ApproveRegistrationWorkflow(reg) send_confirm_email = workflow.default_send_confirm_email invite_to_slack = workflow.default_invite_to_slack default_section = workflow.default_section if workflow.is_late: retroactive_byes = workflow.default_byes late_join_points = workflow.default_ljp else: retroactive_byes = None late_join_points = None workflow.approve_reg(request, None, send_confirm_email, invite_to_slack, default_section, retroactive_byes, late_join_points) count += 1 self.message_user(request, '%d approved.' % count, messages.INFO) return redirect('admin:tournament_registration_changelist')
def app_add(request): if request.method == 'POST': form = AppAddForm(request.POST) if form.is_valid(): if not App.objects.filter(app_domain=form.cleaned_data['app_name']): f = form.save(commit=False) f.app_key = random_str() f.save() messages.add_message(request, messages.SUCCESS, '??????') return HttpResponseRedirect(reverse('app:app_list')) messages.add_message(request, messages.ERROR, '???????????????') messages.add_message(request, messages.ERROR, 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors))) return HttpResponseRedirect(reverse('app:app_add')) else: data = Policy.objects.all() return render_to_response('app/list.html', {'data': data}, context_instance=RequestContext(request))
def app_edit(request): if request.method == 'POST': msg = '????' form = AppEditForm(request.POST) if form.is_valid() and App.objects.filter(app_id=form.cleaned_data['app_id']): f = form.save(commit=False) f.app_id = form.cleaned_data['app_id'] f.app_key = App.objects.get(pk=form.cleaned_data['app_id']).app_key f.save() else: msg = '??????????!' messages.add_message(request, messages.INFO, msg) return HttpResponseRedirect(reverse('app:app_list')) else: messages.add_message(request, messages.ERROR, '??????') return HttpResponseRedirect(reverse('app:app_list'))
def user_otp(request, uid): msg = 'OTP?????' try: data = User.objects.get(pk=uid) profile = UserProfile.objects.get(user=data) profile.otp = pyotp.random_base32() profile.save() messages.add_message(request, messages.SUCCESS, msg) return HttpResponseRedirect(reverse('system:system_user_list')) except User.DoesNotExist: msg = '??????' except UserProfile.DoesNotExist: msg = '???????!' UserProfile(user=data, otp=pyotp.random_base32(), avatar='').save() except Exception, e: msg = '????: ' + e.message messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse('system:system_user_list'))
def group_add(request): if request.method == 'POST': name = request.POST.get('name') permission = request.POST.getlist('permission') try: Group.objects.get(name=name) res, msg = False, 'GroupIsExists!' except Group.DoesNotExist: g = Group(name=name) g.permissions = permission g.save() # for p in permission: # g.permissions.add(p) res, msg = True, 'Create Success!' if res: messages.add_message(request, messages.SUCCESS, msg) else: messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse('system:system_group_list')) else: data = Permission.objects.all() return render_to_response('system/group_create.html', {'data': data}, context_instance=RequestContext(request))
def group_edit(request, gid): if request.method == 'POST': gid = request.POST.get('gid') name = request.POST.get('name') permission = request.POST.getlist('permission') try: g = Group.objects.get(pk=gid) g.name = name g.permissions = permission g.save() res, msg = True, 'role?edit success?' except User.DoesNotExist: res, msg = False, 'role?not exists?' if res: messages.add_message(request, messages.SUCCESS, msg) else: messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse('system:system_group_list')) else: data = Group.objects.get(pk=gid) group_perms = data.permissions.all() all_perms = Permission.objects.all() return render_to_response('system/group_edit.html', {'data': data, 'group_perms': group_perms, 'all_perms': all_perms}, context_instance=RequestContext(request))
def permit_edit(request, pid): if request.method == 'POST': pid = request.POST.get('id') name = request.POST.get('name') try: g = Permission.objects.get(pk=pid) g.name = name g.save() res, msg = True, 'Success!' except Permission.DoesNotExist: res, msg = False, 'PermissionNotExists!' if res: messages.add_message(request, messages.SUCCESS, msg) else: messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse('system:system_permit_list')) else: data = Permission.objects.get(pk=pid) content_type_list = ContentType.objects.all() return render_to_response('system/permit_edit.html', {'data': data, 'content_type_list': content_type_list}, context_instance=RequestContext(request))
def permit_delete(request, pid): """ ???? :param pid: :param request: :return: """ page = int(request.REQUEST.get('page', 1)) try: Permission.objects.get(pk=pid).delete() msg = '???????codename?' + p.codename + ', name:' + str(p.name) messages.add_message(request, messages.SUCCESS, msg) except Permission.DoesNotExist: msg = 'PermissionNotExists' messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse('system:system_permit_list') + '?page=' + str(page))
def user_add(request): form = UsersAddForm(request.POST) message_error = True msg = '??????' if form.is_valid(): if not Users.objects.filter(users_name=form.cleaned_data['users_name']): m2 = hashlib.md5() m2.update(form.cleaned_data['users_password']) f = form.save(commit=False) f.users_password = m2.hexdigest() f.users_create_time = datetime.now() f.users_otp = pyotp.random_base32() f.save() msg = '????' message_error = False else: msg = 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors)) if message_error: messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse('users:user_add')) else: messages.add_message(request, messages.SUCCESS, msg) return HttpResponseRedirect(reverse('users:user_list'))
def policy_edit(request): if request.method == 'POST': form = PolicyEditForm(request.POST) message_error, msg = False, '????' if form.is_valid(): try: p = Policy.objects.get(policy_default__exact=1) if form.cleaned_data["policy_default"] == 1 and p.policy_id != form.cleaned_data["policy_id"]: message_error, msg = True, '??????????????????' else: f = form.save(commit=False) f.policy_id = form.cleaned_data["policy_id"] f.save() except Policy.DoesNotExist: try: if Policy.objects.filter(policy_id=form.cleaned_data["policy_id"]): f = form.save(commit=False) f.policy_id = form.cleaned_data["policy_id"] f.save() except Policy.DoesNotExist: message_error, msg = True, '??????????' else: message_error, msg = True, 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors)) render_message(request, message_error, msg) return HttpResponseRedirect(reverse('policy:policy_list'))
def policy_rule_add(request, rule_policy): if request.method == 'POST': form = PolicyRuleAddForm(request.POST) if form.is_valid(): if not PolicyRule.objects.filter(rule_policy=rule_policy).filter( rule_value=form.cleaned_data['rule_value']): f = form.save(commit=False) f.save() messages.add_message(request, messages.SUCCESS, '??????') return HttpResponseRedirect(reverse('policy:policy_rule_list', args=[rule_policy])) messages.add_message(request, messages.ERROR, '???????????????') messages.add_message(request, messages.ERROR, 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors))) return HttpResponseRedirect(reverse('policy:policy_rule_list', args=[rule_policy])) else: return render_to_response('policy/rule/list.html', {'rule_policy': rule_policy}, context_instance=RequestContext(request))
def policy_rule_edit(request, policy_id): if request.method == 'POST': msg = '????' form = PolicyRuleEditForm(request.POST) if form.is_valid(): if PolicyRule.objects.filter(rule_id=form.cleaned_data["rule_id"]): f = form.save(commit=False) f.rule_id = form.cleaned_data["rule_id"] f.save() else: msg = '?????!' messages.add_message(request, messages.INFO, msg) else: msg = 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors)) messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse('policy:policy_rule_list', args=[policy_id])) else: messages.add_message(request, messages.ERROR, '?????') return HttpResponseRedirect(reverse('policy:policy_rule_list', args=[policy_id]))
def admin_make_inquiry_requests(self, request): if not request.method == 'POST': raise PermissionDenied if not self.has_change_permission(request): raise PermissionDenied try: inquiry = Inquiry.objects.get(pk=request.POST.get('inquiry_pk')) except Inquiry.DoesNotExist: raise Http404 try: make_inquiry_requests_from_file(inquiry, request.FILES['file']) except ValueError as e: messages.add_message(request, messages.ERROR, e.message) return redirect('admin:confrontiv_inquiry_changelist') return redirect('admin:confrontiv_inquiryrequest_changelist')
def form_valid(self, form): try: self.object = form.save() messages.add_message(self.request, messages.SUCCESS, "Your event has been created.") return super(ModelFormMixin, self).form_valid(form) except BaseException, e: if hasattr(e, '__iter__'): for exc in e: messages.add_message(self.request, messages.ERROR, "Error creating your event -- %s" % exc[1][0]) if hasattr(form, exc[0]): form.add_error(exc[0], exc[1][0]) elif isinstance(e, UnicodeError): field = e[1][e[1][0:e[3]].rfind('&')+1:e[1][0:e[3]].rfind('=')] messages.add_message(self.request, messages.ERROR, "Error creating your event -- You had some special characters in your %s field, please remove those and try again." % field) if field in form.fields: form.add_error(field, "Please remove special characters and try again.") return super(EventCreate, self).form_invalid(form)
def form_valid(self, form): try: self.object = form.save() messages.add_message(self.request, messages.SUCCESS, "Your event has been updated.") return super(ModelFormMixin, self).form_valid(form) except BaseException, e: if hasattr(e, '__iter__'): for exc in e: messages.add_message(self.request, messages.ERROR, "Error creating your event -- %s" % exc[1][0]) if hasattr(form, exc[0]): form.add_error(exc[0], exc[1][0]) elif isinstance(e, UnicodeError): field = e[1][e[1][0:e[3]].rfind('&')+1:e[1][0:e[3]].rfind('=')] if field in form.fields: form.add_error(field, "Please remove special characters and try again.") messages.add_message(self.request, messages.ERROR, "Error updating your event -- You had some special characters in your %s field, please remove those and try again." % field) return super(EventEdit, self).form_invalid(form)
def delete(request, contest_id, group_id): if not request.user.has_perm('manage_contest', Contest.objects.get(pk=contest_id)): raise PermissionDenied return HttpResponseRedirect(reverse('contest_details', args=[contest_id])) else: try: Group.objects.get(pk=group_id).delete() messages.add_message(request, messages.SUCCESS, "Group has been successfully deleted.") except ObjectDoesNotExist: messages.add_message(request, messages.ERROR, "Group does not exists.") return HttpResponseRedirect(reverse('contest_details', args=[contest_id]))
def fetch_task(request, contest_id): contest = Contest.objects.get(pk=contest_id) if not request.user.has_perm('manage_contest', contest): raise PermissionDenied elif request.method == 'POST': form = TaskFetchForm(request.POST) if form.is_valid(): fetched_task = copy_task(form) fetched_task.contest = contest if save_task(fetched_task): messages.add_message( request, messages.SUCCESS, 'New task has been added to contest %s.' % contest.name) add_task_to_groups(contest, fetched_task) else: messages.add_message( request, messages.ERROR, 'Unable to fetch task %s. Please report this accident' ' to administrator.' % fetched_task) return HttpResponseRedirect( reverse('contest_details', args=[contest_id]) + '?current_tab=tasks')
def dispatch(self, request, *args, **kwargs): # get the game by the id self.game = Game.get_by_id(kwargs['game_id']) user = get_user(request) # check to see if the game is open and available for this user # if this player is the creator, just return if self.game.creator == user or self.game.opponent == user: return super(GameView, self).dispatch(request, *args, **kwargs) # if there is no opponent and the game is not yet completed, # set the opponent as this user if not self.game.opponent and not self.game.completed: self.game.opponent = user self.game.save() return super(GameView, self).dispatch(request, *args, **kwargs) else: messages.add_message(request, messages.ERROR, 'Sorry, the selected game is not available.') return redirect('/lobby/')
def create_users(self, request, queryset): for author in queryset.all(): if author.user: continue try: author.user = User.objects.create( username=author.login, email=author.email, first_name=author.first_name or '', last_name=author.last_name or '', ) author.save() except Exception as e: self.message_user(request, _('Failed to create user {}: {}').format(author.login, e), messages.ERROR) else: self.message_user(request, _('Successfully created user {}').format(author.login), messages.SUCCESS)
def find_users(self, request, queryset): for author in queryset.all(): if author.user: continue try: author.user = User.objects.get(username=author.login) except User.DoesNotExist: pass if not author.user: author.user = User.objects.filter(email=author.email).first() if not author.user: author.user = User.objects.filter(first_name=author.first_name, last_name=author.last_name).first() if author.user: author.save() self.message_user( request, _('Successfully found user {} for author').format(author.user, author), messages.SUCCESS) else: self.message_user(request, _('Failed to find user for author {}').format(author), messages.ERROR)
def selection_valid(modeladmin, request, queryset): """ Verify that the selected registration profiles are ready for action Args: modeladmin: the current admin interface request: request object sent with admin action queryset: queryset of objects selected Returns: boolean, indicating whether selection is valid """ # Check whether selection contains profiles of people whose identity has not been confirmed. if queryset.filter(identity_confirmed=False).exists(): modeladmin.message_user(request, "One or more users have not confirmed their identity", level=messages.ERROR) return False # Check whether selection contains inactive (dealt with) registration profiles if queryset.filter(active=False).exists(): modeladmin.message_user(request, "One or more registration profiles are inactive (already dealt with)", level=messages.ERROR) return False return True
def dispatch(self, request, *args, **kwargs): """ If an :model:`EmailChange` object that has been created by the user is not found, the user will be redirected to :view:`EmailChangeCreateView`. """ try: object = EmailChange.objects.filter(user=request.user).get() except EmailChange.DoesNotExist: msg = _("No email address change request was found. Either an old " "one has expired or a new one has not been requested.") messages.add_message(request, messages.ERROR, msg, fail_silently=True) logger.error('No email address change request found.') #return HttpResponseRedirect(reverse_lazy('change_email_create')) object = None self.object = object return super(EmailChangeConfirmView, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): """ If an :model:`EmailChange` object that has been created by the user is found, the user will be redirected to :view:`EmailChangeDetailView`. """ if EmailChange.objects.filter(user=request.user).count(): msg = _("An email address change request was found. It must" " be deleted before a new one can be requested.") messages.add_message(request, messages.ERROR, msg, fail_silently=True) logger.error('Pending email address change request found.') object = EmailChange.objects.filter(user=request.user).get() return HttpResponseRedirect(reverse_lazy('change_email_detail', args=[object.pk])) return super(EmailChangeCreateView, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): """ If an :model:`EmailChange` object that has been created by the user is not found, the user will be redirected to :view:`EmailChangeCreateView`. """ if not EmailChange.objects.filter(user=request.user).count(): msg = _("No email address change request was found. Either an " "old one has expired or a new one has not been requested.") messages.add_message(request, messages.ERROR, msg, fail_silently=True) logger.error('No email address change request found.') return HttpResponseRedirect(reverse_lazy('change_email_create')) return super(EmailChangeDeleteView, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): """ If an :model:`EmailChange` object that has been created by the user is not found, the user will be redirected to :view:`EmailChangeCreateView`. """ if not EmailChange.objects.filter(user=request.user).count(): msg = _("No email address change request was found. Either an " "old one has expired or a new one has not been requested.") messages.add_message(request, messages.ERROR, msg, fail_silently=True) logger.error('No email address change request found.') return HttpResponseRedirect(reverse_lazy('change_email_create')) return super(EmailChangeDetailView, self).dispatch(request, *args, **kwargs)
def delete(self, request, *args, **kwargs): self.object = self.get_object() success_url = self.get_success_url() # make sure user is not a referent who cannot quit groups if self.object.is_referent: messages.add_message( request, messages.ERROR, _("Les animateurs ne peuvent pas quitter un groupe sans avoir abandonné leur role.") ) else: self.object.delete() messages.add_message( request, messages.SUCCESS, format_html( _("Vous avez bien quitté le groupe <em>{}</em>"), self.object.supportgroup.name ) ) return HttpResponseRedirect(success_url)
def artist_login(request): if request.method == 'GET': if request.user.username != '': return redirect('/musician/artist/'+request.user.username) else: return render(request,'musician/login.html') else: username = request.POST['username'] password = request.POST['password'] login_user = authenticate(username=username, password=password) if login_user is not None: login(request, login_user) return redirect('/musician/artist/'+username+'/') else: messages.add_message(request, messages.ERROR, "Login Invalid, Please Try Again") return redirect('/musician/login') # register handler
def register(request): if request.method == 'GET': return render(request,'musician/register.html') else: try: username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] user = User.objects.create_user(username, email, password) user.save() login_user = authenticate(username=username, password=password) login(request, login_user) return redirect('/musician/artist/'+username+'/') except Exception as e: messages.add_message(request, messages.ERROR, "Registration Failed: Duplicated Username") logging.exception("message") return redirect('/musician/register/') # logout user
def statistics(request, artist_id, music_id): if request.user.is_authenticated and request.user.username == artist_id: context = {} context['artist'] = artist_id context['music_name'] = Music.objects.get(id=music_id).title today = datetime.now() stats = {} nodata = 1 print music_id for i in range(1,8): target_day = today-timedelta(i) target_day = target_day.strftime("%Y-%m-%d") print target_day (date, count, rank) = backend_client.run_request(int(music_id),target_day) if rank != 0: nodata = 0; stats[i] = rank if nodata == 1: stats[0] = 0 context['rank'] = stats; return render(request,'musician/statistics.html', context) else: messages.add_message(request, messages.ERROR, "No Access to This Page") logging.exception("message") return redirect('/musician/')
def do(self, action_context, view, email, *args, **kwargs): user = action_context.extra_context.get('user') if not user: msg = _("We haven't found any account with email {0}").format(email) messages.add_message(action_context.request, messages.ERROR, msg) logger.info(("Recover password not sent to {0} (email not found)" ).format(email)) # Set the initial form with the next value uri = get_redirect_url(action_context.request) # Get the uri from the url first if not uri: form = action_context.extra_context["form"] # Try second time from the form uri = form.get_redirect_uri() form = view.get_form_class()(initial={ 'redirect_uri': uri}) action_context.response = view.render_to_response( view.get_context_data(form=form)) action_context.break_chain = True return super().do(action_context, view, email, *args, **kwargs)
def do(self, action_context, view, impersonate_user, *args, **kwargs): user = action_context.extra_context.get('user') if user and not action_context.extra_context.get('invalid_jwt_version'): if not user.project_permissions.filter( key=settings.APP_PERMISSION_KEYS['impersonate']).exists(): logger.warning("User '{0}' doesn't have permission to impersonate user '{1}'".format( user.id, impersonate_user.id)) action_context.break_chain = True # Add an error message messages.add_message( action_context.request, messages.ERROR, _("You don't have impersonation permission")) return super().do(action_context, view, impersonate_user, *args, **kwargs)