def delete(request, uuid): """Handle deleting connections, showing a confirmation dialog first. On GET, display a confirmation page. On POST, delete the connection. """ if request.method == 'POST': try: name = network.delete_connection(uuid) messages.success(request, _('Connection {name} deleted.') .format(name=name)) except network.ConnectionNotFound: messages.error(request, _('Failed to delete connection: ' 'Connection not found.')) return redirect(reverse_lazy('networks:index')) try: connection = network.get_connection(uuid) name = connection.get_id() except network.ConnectionNotFound: messages.error(request, _('Failed to delete connection: ' 'Connection not found.')) return redirect(reverse_lazy('networks:index')) return TemplateResponse(request, 'connections_delete.html', {'title': _('Delete Connection'), 'subsubmenu': subsubmenu, 'name': name})
def get_redirect_url(self, *args, **kwargs): event_id = kwargs["event_id"] verify = requests.get( url="https://www.google.com/recaptcha/api/siteverify", params={ "secret": settings.GOOGLE_RECAPTCHA_SECRET, "response": self.request.POST['g-recaptcha-response'] } ) data = json.loads(verify.text) if not data['success']: messages.error(self.request, _("Authentication failed.")) return reverse_lazy('event:detail', kwargs={'pk': event_id}) text = self.request.POST["text"] if text.strip() != "": comment = Comment( user=self.request.user, event=Event.objects.get(pk=event_id), text=text, ) comment.save() return reverse_lazy('event:detail', kwargs={'pk': event_id})
def __init__(self): self.create = login_required(CreateView.as_view( model=self.model, fields=('name',), success_url=reverse_lazy('laboratory:laboratory_list'), template_name=self.template_name_base + 'form.html' )) self.edit = login_required(UpdateView.as_view( model=self.model, fields=('name',), success_url=reverse_lazy('laboratory:laboratory_list'), template_name=self.template_name_base + 'form.html' )) self.delete = login_required(DeleteView.as_view( model=self.model, success_url=reverse_lazy('laboratory:laboratory_list'), template_name=self.template_name_base + 'delete.html' )) self.list = login_required(ListView.as_view( model=self.model, paginate_by=10, template_name=self.template_name_base + 'list.html' ))
def add_redmine_activity(project,sprintusertoryForm, request, object): bugtracking = BugTrackingFactory.getConnection(project=project) try: version = sprintusertoryForm[0].sprint.reference except: version = 1 artType = ArtifactType.objects.filter( level=3 ).first() if request.is_secure(): url = 'https://' + get_current_site(request).domain + str( reverse_lazy('main:userstory-detail', kwargs={'pk': object.pk})) else: url = 'http://' + get_current_site(request).domain + str( reverse_lazy('main:userstory-detail', kwargs={'pk': object.pk})) issue = bugtracking.addIssueFromUserStory( project_id=project.id, subject=object.title + ' ' + artType.trace_code + object.code, tracker_id=project.issueOnInsertUserStory, description=object.description + ' ' + url, fixed_version_id=version, ) userstory = UserStory.objects.filter(project=project, code=object.code).get() Artifact.objects.create(project=project, reference=issue.id, type=artType, userstory=userstory)
def get_success_url(self): site = Site.objects.get_current() # If user came from Speedy Match and his/her Email address is confirmed, redirect to Matches page. if (site.id == django_settings.SPEEDY_MATCH_SITE_ID): if (self.request.user.email_addresses.filter(is_confirmed=True).count() == 1): return reverse_lazy('matches:list') return reverse_lazy('accounts:edit_profile_emails')
def GetConversation(request): """Conversation search form""" if request.method == 'POST': u = ForumUser.objects.exclude(username=request.user)\ .filter(username__istartswith=request.POST['query']) if u.count() == 1: c = Conversation.objects.filter(participants=request.user)\ .filter(participants=u.get()) if c.count() == 1: c = c.get() tag = '#' + str(c.messages.latest().pk) return HttpResponseRedirect( reverse_lazy('pm:msg', kwargs={'pk': c.pk}) + tag) else: messages.error( request, ("Il n'existe pas de conversation avec" " cet utilisateur : {:s}.".format(u.get().username)) ) elif u.count() > 1: messages.error( request, "Plusieurs utilisateurs possibles : {:s}.".format( ", ".join([u.username for u in u])) ) else: messages.error(request, "Aucun utilisateur trouvé.") return HttpResponseRedirect(reverse_lazy('pm:top'))
def get_success_url(self): if 'sprint_id' in self.kwargs: return reverse_lazy('main:userstory', kwargs={'sprint_id': self.kwargs['sprint_id']}) elif 'requeriment_id' in self.kwargs: return reverse_lazy('main:userstory', kwargs={'requeriment_id': self.kwargs['requeriment_id']}) else: return reverse_lazy('main:userstory')
def booking_sysadm(request, pk, action): try: if not request.user.is_superuser: raise UserNotAllowed booking = Booking.objects.select_related().get(id=pk) if action == 'delete': from_date = booking.from_date to_date = booking.to_date settlement = booking.settlement while from_date < to_date: avail = Availability.objects.get(room=settlement.room, date=from_date) avail.placecount += 1 avail.save() from_date += timedelta(days=1) # TODO RETURN MAIL #booking_delete_client_mail(booking) booking.delete() url = reverse_lazy('bookings_list') elif action == 'enable': booking.enabled = True booking.save() # TODO RETURN MAIL #booking_new_hotel_mail(booking) url = reverse_lazy('booking_admin_detail', args=[booking.uuid, ]) else: raise UserNotAllowed return HttpResponseRedirect(url) except: raise Http404
def get_context_data(self, **kwargs): context = super(ProjectDeleteView, self).get_context_data() breadcrumbs = ( {'link': reverse_lazy('main:home'), 'class': '', 'name': _('Home')}, {'link': reverse_lazy('main:project-list'), 'class': 'active', 'name': _('Project')}, {'link': '#', 'class': 'active', 'name': _('Update')}, ) return context
def get_success_url(self): if (self.step >= len(SpeedyMatchSiteProfile.settings.SPEEDY_MATCH_SITE_PROFILE_FORM_FIELDS)): if (self.request.user.has_confirmed_email()): return reverse_lazy('matches:list', kwargs={'step': self.step}) else: return reverse_lazy('accounts:edit_profile_emails', kwargs={'step': self.step}) else: return reverse_lazy('accounts:activate', kwargs={'step': self.step + 1})
def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) user_form = UserDataForm(instance=self.request.user) profile = get_object_or_404(Profile, user=self.request.user) profile_form = ProfileForm(instance=profile) user_form.helper.form_action = reverse_lazy('userdataUpdate', args=[self.request.user.pk]) profile_form.helper.form_action = reverse_lazy('profileUpdate', args=[profile.pk])
def test_inserting_reverse_lazy_into_string(self): self.assertEqual( 'Some URL: %s' % reverse_lazy('some-login-page'), 'Some URL: /login/' ) if six.PY2: self.assertEqual( b'Some URL: %s' % reverse_lazy('some-login-page'), 'Some URL: /login/' )
def get_context_data(self, **kwargs): context = super(SprintDeleteView, self).get_context_data() context['breadcrumbs'] = ( {'link': reverse_lazy('main:home'), 'class': '', 'name': _('Home')}, {'link': reverse_lazy('main:sprint'), 'class': '', 'name': _('Sprint')}, {'link': reverse_lazy('main:sprint-details', kwargs={'sprint_id': context['sprint'].id}), 'class': '', 'name': str(context['sprint'].title)}, {'link': '#', 'class': '', 'name': _('Delete')} ) return context
def add_shortcut(): """Add shortcut in frontpage.""" download_profile = \ format_lazy(_('<a class="btn btn-primary btn-sm" href="{link}">' 'Download Profile</a>'), link=reverse_lazy('openvpn:profile')) frontpage.add_shortcut( 'openvpn', name, short_description=short_description, details=description + [download_profile], configure_url=reverse_lazy('openvpn:index'), login_required=True)
def sidebar_links(self): links = [ (_('Start'), reverse_lazy("dashboard:personal_overview")) ] from clothing.models import Settings clothing_settings = Settings.instance() if clothing_settings is not None and clothing_settings.clothing_ordering_enabled: links.append((_('Kleidungsbestellung'), reverse_lazy('clothing:overview'))) return links
def NewMessage(request, pk): if request.method == 'POST': c = get_object_or_404(Conversation, pk=pk) m = Message.objects.create( conversation=c, author=request.user, content_plain=request.POST['content_plain']) pm_counter(request, c) qs = '?page=last#' + str(m.pk) return HttpResponseRedirect( reverse_lazy('pm:msg', kwargs={'pk': pk}) + qs) else: return HttpResponseRedirect(reverse_lazy('pm:top'))
def test_post_invalid_form(self): """Invalid form.""" response = self.client.get(reverse_lazy('delivery:meal')) req = {} req['_update'] = 'Next: Print Kitchen Count' req['maindish'] = 'wrong' response = self.client.post(reverse_lazy('delivery:meal'), req) self.assertIn( ugettext( 'Select a valid choice. That choice is not one of ' 'the available choices.').encode(response.charset), response.content )
def get_urls(self): from django.contrib.auth import views as auth_views from oscar.views.decorators import login_forbidden urls = [ url(r'^$', RedirectView.as_view(url=reverse_lazy('catalogue:index')), name='home'), url(r'^catalogue/', self.catalogue_app.urls), url(r'^basket/', self.basket_app.urls), url(r'^checkout/', self.checkout_app.urls), url(r'^accounts/', self.customer_app.urls), url(r'^search/', self.search_app.urls), url(r'^dashboard/', self.dashboard_app.urls), url(r'^offers/', self.offer_app.urls), # Password reset - as we're using Django's default view functions, # we can't namespace these urls as that prevents # the reverse function from working. url(r'^password-reset/$', login_forbidden( auth_views.PasswordResetView.as_view( form_class=self.password_reset_form, success_url=reverse_lazy('password-reset-done'), template_name='oscar/registration/password_reset_form.html' ) ), name='password-reset'), url(r'^password-reset/done/$', login_forbidden(auth_views.PasswordResetDoneView.as_view( template_name='oscar/registration/password_reset_done.html' )), name='password-reset-done'), url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', login_forbidden( auth_views.PasswordResetConfirmView.as_view( form_class=self.set_password_form, success_url=reverse_lazy('password-reset-complete'), template_name='oscar/registration/password_reset_confirm.html' ) ), name='password-reset-confirm'), url(r'^password-reset/complete/$', login_forbidden(auth_views.PasswordResetCompleteView.as_view( template_name='oscar/registration/password_reset_complete.html' )), name='password-reset-complete'), ] return urls
def test_reverse_lazy_decodes(self): "Ensure reverse_lazy works in the test client" data = {'var': 'data'} response = self.client.get(reverse_lazy('get_view'), data) # Check some response details self.assertContains(response, 'This is a test')
def PipelineDefaultNewView(request): new_pipeline = Pipeline() new_pipeline.userprofile = request.user.userprofile new_pipeline.save() return HttpResponseRedirect(reverse_lazy('pipeline:detail', kwargs={'pk': new_pipeline.pk}))
def get_context_data(self, **kwargs): context = super(FieldMappingEditView, self).get_context_data(**kwargs) context["mapping_id"] = self.kwargs.get('mapping_id') context['submit_url'] = reverse_lazy(self.submit_url, args=(context['mapping_id'], )) return context
def password_reset_confirm(request, uidb64=None, token=None): kwargs = { 'template_name': 'account/password_reset_from_key.html', 'success_url': reverse_lazy('account:reset-password-complete'), 'token': token, 'uidb64': uidb64} return PasswordResetConfirm.as_view(**kwargs)(request, **kwargs)
def get_success_url(self): if self.object.status == "参加中": participations = self.object.frame.participation_set waiting_list = participations.filter(status="キャンセル待ち") \ .order_by('created') if len(waiting_list) > 0: carry_up = waiting_list.first() carry_up.status = "参加中" carry_up.save() # Send Email template = get_template("email/carry_up.txt") context = Context({'user': carry_up.user, 'event': carry_up.event}) content = template.render(context) subject, message = content.split("\n", 1) # XXX: Hardcoded From address send_mail(subject, message, "*****@*****.**", [carry_up.user.email]) messages.success(self.request, _("Canceled your participation.")) return reverse_lazy('event:detail', kwargs={ 'pk': self.kwargs['event_id'] })
def handle(self, request, data): redirect = reverse_lazy('horizon:project:instances:index') fip_id = data['fip'] fips = [fip for fip in self.fips if fip.id == fip_id] if not fips: messages.error(request, _("The specified floating IP no longer exists."), redirect=redirect) fip = fips[0] try: if data['is_release']: api.neutron.tenant_floating_ip_release(request, fip_id) messages.success( request, _("Successfully disassociated and released " "floating IP %s") % fip.ip) else: api.neutron.floating_ip_disassociate(request, fip_id) messages.success( request, _("Successfully disassociated floating IP %s") % fip.ip) except Exception: exceptions.handle( request, _('Unable to disassociate floating IP %s') % fip.ip, redirect=redirect) return True
def create(request): """Form to create a wiki or blog.""" form = None if request.method == 'POST': form = IkiwikiCreateForm(request.POST, prefix='ikiwiki') if form.is_valid(): if form.cleaned_data['site_type'] == 'wiki': _create_wiki(request, form.cleaned_data['name'], form.cleaned_data['admin_name'], form.cleaned_data['admin_password']) elif form.cleaned_data['site_type'] == 'blog': _create_blog(request, form.cleaned_data['name'], form.cleaned_data['admin_name'], form.cleaned_data['admin_password']) site = form.cleaned_data['name'].replace(' ', '') frontpage.add_shortcut( 'ikiwiki_' + site, site, url='/ikiwiki/' + site, login_required=False, icon='ikiwiki') return redirect(reverse_lazy('ikiwiki:manage')) else: form = IkiwikiCreateForm(prefix='ikiwiki') return TemplateResponse(request, 'ikiwiki_create.html', {'title': _('Create Wiki or Blog'), 'form': form, 'subsubmenu': subsubmenu})
def test_lazy_base_url_init(self): """ FileSystemStorage.__init__() shouldn't evaluate base_url. """ storage = FileSystemStorage(base_url=reverse_lazy('app:url')) with self.assertRaises(NoReverseMatch): storage.url(storage.base_url)
def get_context_data(self, **kwargs): context = super(GroupCreateView, self).get_context_data(**kwargs) context["service_id"] = self.kwargs.get('service_id') context['submit_url'] = reverse_lazy(self.submit_url, args=(context['service_id'], )) return context
def test_reverse_lazy_decodes(self): "Ensure reverse_lazy works in the test client" data = {"var": "data"} response = self.client.get(reverse_lazy("get_view"), data) # Check some response details self.assertContains(response, "This is a test")
def get_context_data(self, **kwargs): context = super(FieldThresholdEditView, self).get_context_data(**kwargs) context["threshold_id"] = self.kwargs.get('threshold_id') context['submit_url'] = reverse_lazy(self.submit_url, args=(context['threshold_id'], )) return context
def get_context_data(self, **kwargs): context = super(FieldThresholdCreateView, self).get_context_data(**kwargs) context["field_id"] = self.kwargs.get('field_id') args = (context['field_id'],) context['submit_url'] = reverse_lazy(self.submit_url, args=args) return context
class PostDelete(LoginRequiredMixin, DeleteView): model = Post success_url = reverse_lazy('dashboard')
class MyPageScheduleDelete(OnlyScheduleMixin, generic.DeleteView): model = Schedule success_url = reverse_lazy('booking:my_page')
class CityUpdateView(SuccessMessageMixin, LoginRequiredMixin, UpdateView): model = City form_class = CityForm template_name = 'cities/update.html' success_url = reverse_lazy('cities:home') success_message = "City was updated"
class VHostCreate(LoginRequiredMixin, SuccessMessageMixin, SuccessActionFormMixin, CreateView): model = VHost fields = ('name', 'domain', 'cert', 'use_letsencrypt') success_url = reverse_lazy('web_vhost_list') success_message = _("%(name)s was created successfully") success_action = update_vhosts
from django.conf.urls import url from django.urls import reverse_lazy from django.views.generic.base import RedirectView from user import views urlpatterns = [ url(r'^login/$', views.login, name='account_login'), url(r'^callback/(?P<provider>[0-9A-Za-z_\-]+)/$', views.callback, name='callback'), url(r'^signup/$', RedirectView.as_view(url=reverse_lazy('account_signup_typed', kwargs={'u_type': 'hacker'})), name='account_signup'), url(r'^register/sponsor/$', views.SponsorRegister.as_view(), name='sponsor_signup'), url(r'^signup/(?P<u_type>[a-z_\-]{1,10})/$', views.signup, name='account_signup_typed'), url(r'^logout/$', views.logout, name='account_logout'), url(r'^activate/(?P<uid>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,40})/$', views.activate, name='activate'), url(r'^password/$', views.set_password, name='set_password'), url(r'^password_reset/$', views.password_reset, name='password_reset'), url(r'^password_reset/done/$', views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uid>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,40})/$', views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', views.password_reset_complete, name='password_reset_complete'), url(r'^verify/$', views.verify_email_required, name='verify_email_required'), url(r'^verify/send$', views.send_email_verification, name='send_email_verification'), url(r'^profile/$', views.UserProfile.as_view(), name='user_profile'), url(r'^profile/delete/$', views.DeleteAccount.as_view(), name='user_profile_delete'), ]
class ArticleDelete(LoginRequiredMixin, DeleteView): model = Article success_url = reverse_lazy('dashboard')
class TweetDeleteView(LoginRequiredMixin, DeleteView): model = Tweet success_url = reverse_lazy("tweets:list") template_name = 'tweets/delete_confirm.html'
class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html'
class VHostDelete(LoginRequiredMixin, SuccessActionDeleteMixin, DeleteView): model = VHost success_url = reverse_lazy('web_vhost_list') success_action = update_vhosts
class VHostUpdate(LoginRequiredMixin, SuccessActionFormMixin, UpdateView): model = VHost fields = ['cert', 'use_letsencrypt'] success_url = reverse_lazy('web_vhost_list') success_action = update_vhosts
class CompanyDeleteView(DeleteView): model = Company success_url = reverse_lazy('companies')
class BookDelete(PermissionRequiredMixin, DeleteView): model = Book success_url = reverse_lazy('books') permission_required = 'catalog.can_mark_returned'
def get_success_url(self): return reverse_lazy('helpme_admin:ticket-detail', args=[self.object.uuid])
class SSLCertDelete(LoginRequiredMixin, DeleteView): model = SSLCert success_url = reverse_lazy('web_sslcert_list')
class RegisterView(generic.CreateView): """Allows user to register with the custom form we created""" form_class = CustomUserForm success_url = reverse_lazy('login') template_name = 'registration/register.html'
class AuthorDelete(PermissionRequiredMixin, DeleteView): model = Author success_url = reverse_lazy('authors') permission_required = 'catalog.can_mark_returned'
class SignUp(CreateView): form_class=forms.UserCreateForm success_url=reverse_lazy('login') template_name='accounts/signup.html'
def get_url(self, obj): return reverse_lazy("profiles:detail", kwargs={"username": obj.username })
class CourseDeleteView(PermissionRequiredMixin, OwnerCourseMixin, DeleteView): template_name = 'course/manage/course/delete.html' success_url = reverse_lazy('manage_course_list') permission_required = 'courses.delete_course'
class ProductDeleteView(PermissionRequiredMixin, DeleteView): model = Product template_name = 'product/product_delete.html' success_url = reverse_lazy('webapp:index') permission_required = 'webapp.delete_product'
class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin): fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') template_name = 'course/manage/course/form.html'
class ProductCategoryUpdate(OnlySuperUserMixin, PageTitleMixin, UpdateView): page_title = 'админка/категрии/редактирование' model = ProductCategory success_url = reverse_lazy('my_admin:categories_read') form_class = AdminProductCategoryCreateForm pk_url_kwarg = 'category_pk'
class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin): model = Course fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list')
class ProductCategoryCreate(OnlySuperUserMixin, PageTitleMixin, CreateView): page_title = 'админка/категрии/создание' model = ProductCategory success_url = reverse_lazy('my_admin:categories_read') form_class = AdminProductCategoryCreateForm
class PersonajeDelete(DeleteView): model = Personaje success_url = reverse_lazy('ListaPersonajes')
class SignUpView(CreateView): form_class = CustomUserCreationForm template_name = 'sign_up.html' success_url = reverse_lazy('login')
class MyPageSchedule(OnlyScheduleMixin, generic.UpdateView): model = Schedule fields = ('start', 'end', 'name') success_url = reverse_lazy('booking:my_page')
class PostDeleteView(DeleteView): model = Post template_name = 'post_delete.html' success_url = reverse_lazy('posts')
def get_success_url(self): return reverse_lazy('contract', kwargs={'pk': self.object.id})
class RegisterUser(CreateView): form_class = UserRegister success_url = reverse_lazy('login') template_name = 'blogapp/signup.html'