本文整理汇总了Python中django.views.generic.View方法的典型用法代码示例。如果您正苦于以下问题:Python generic.View方法的具体用法?Python generic.View怎么用?Python generic.View使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.views.generic
的用法示例。
在下文中一共展示了generic.View方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: approve_moderation
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def approve_moderation(request, revision_id):
revision = get_object_or_404(PageRevision, id=revision_id)
if not revision.page.permissions_for_user(request.user).can_publish():
raise PermissionDenied
if not revision.submitted_for_moderation:
messages.error(request, _("The page '{0}' is not currently awaiting moderation.").format(revision.page.get_admin_display_title()))
return redirect('wagtailadmin_home')
if request.method == 'POST':
revision.approve_moderation()
message = _("Page '{0}' published.").format(revision.page.get_admin_display_title())
buttons = []
if revision.page.url is not None:
buttons.append(messages.button(revision.page.url, _('View live'), new_window=True))
buttons.append(messages.button(reverse('wagtailadmin_pages:edit', args=(revision.page.id,)), _('Edit')))
messages.success(request, message, buttons=buttons)
if not send_notification(revision.id, 'approved', request.user.pk):
messages.error(request, _("Failed to send approval notifications"))
return redirect('wagtailadmin_home')
示例2: activate
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def activate(request, uuid):
"""View responsible for activating user account."""
try:
profile = UserProfile.objects.get(uuid=uuid)
profile.user.is_active = True
profile.user.save()
messages.success(
request,
"""Pomyślnie aktywowałeś użytkownika."""
)
except UserProfile.DoesNotExist:
messages.error(
request,
"""Brak użytkownika spełniającego wymagane kryteria."""
)
return redirect('homepage')
示例3: post
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def post(request, slug, id_):
u"""View responsible for submitting volunteers awarding."""
offer = get_object_or_404(Offer, id=id_)
post_data = request.POST
if post_data.get('csrfmiddlewaretoken'):
del post_data['csrfmiddlewaretoken']
if post_data.get('submit'):
del post_data['submit']
offer.votes = True
offer.save()
context = {
'offer': offer,
}
return render(request, "offers/show_offer.html", context=context)
示例4: get_business_unit_by
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def get_business_unit_by(model, **kwargs):
try:
pk = [v for k, v in kwargs.items() if k.endswith('_id')].pop()
except IndexError:
raise ValueError('View lacks an ID parameter!')
try:
instance = get_object_or_404(model, pk=pk)
except ValueError:
# Sal allows machine serials instead of machine ID in URLs.
# Handle that special case.
if model is Machine:
instance = get_object_or_404(model, serial=pk)
if isinstance(instance, MachineGroup):
return (instance, instance.business_unit)
elif isinstance(instance, Machine):
return (instance, instance.machine_group.business_unit)
else:
return (instance, instance)
示例5: required_level
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def required_level(*decorator_args):
"""View decorator to redirect users without acceptable userprofile..
Wrapped function must have the request object as the first argument.
Args:
*args (server.model.UserProfile.LEVEL_CHOICES) Any number of
user profile level choices that should be permitted access.
"""
def decorator(function):
@wraps(function)
def wrapper(*args, **kwargs):
if args[0].user.userprofile.level not in decorator_args:
return redirect(reverse('home'))
else:
return function(*args, **kwargs)
return wrapper
return decorator
示例6: require_authenticated_permission
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def require_authenticated_permission(permission):
def decorator(cls):
if (not isinstance(cls, type)
or not issubclass(cls, View)):
raise ImproperlyConfigured(
"require_authenticated_permission"
" must be applied to subclasses "
"of View class.")
check_auth = (
method_decorator(login_required))
check_perm = (
method_decorator(
permission_required(
permission,
raise_exception=True)))
cls.dispatch = (
check_auth(check_perm(cls.dispatch)))
return cls
return decorator
示例7: test_invalid_keyword_argument
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def test_invalid_keyword_argument(self):
"""
View arguments must be predefined on the class and can't
be named like a HTTP method.
"""
msg = (
"You tried to pass in the %s method name as a keyword argument "
"to SimpleView(). Don't do that."
)
# Check each of the allowed method names
for method in SimpleView.http_method_names:
with self.assertRaisesMessage(TypeError, msg % method):
SimpleView.as_view(**{method: 'value'})
# Check the case view argument is ok if predefined on the class...
CustomizableView.as_view(parameter="value")
# ...but raises errors otherwise.
msg = (
"CustomizableView() received an invalid keyword 'foobar'. "
"as_view only accepts arguments that are already attributes of "
"the class."
)
with self.assertRaisesMessage(TypeError, msg):
CustomizableView.as_view(foobar="value")
示例8: test_register_view_takes_allow_cdn
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def test_register_view_takes_allow_cdn(self):
router = MixedViewRouter()
router.register_view("view-1", View, name="view-1", allow_cdn=True)
router.register_view("view-2", View, name="view-2", allow_cdn=False)
assert [v.name for v in router.registered_view_urls] == ["view-1", "view-2"]
assert router.registered_view_urls[0].allow_cdn
assert not router.registered_view_urls[1].allow_cdn
示例9: test_register_view_requires_name
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def test_register_view_requires_name(self):
router = MixedViewRouter()
with pytest.raises(TypeError) as err:
router.register_view("view", View, allow_cdn=True)
assert "missing 1 required keyword-only argument: 'name'" in str(err.value)
示例10: test_get_urls_includes_non_viewset_views
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def test_get_urls_includes_non_viewset_views(self):
router = MixedViewRouter()
router.register_view("view", View, name="standalone-view")
urls = router.get_urls()
assert len(urls) == 1
assert urls[0].name == "standalone-view"
示例11: get_success_url
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def get_success_url(self):
return reverse('fieldsight:region-list', kwargs={'pk': self.object.project.id})
# class RegionDeactivateView(View):
#
# def get(self, request, pk, *args, **kwargs):
# region = Region.objects.get(pk=pk)
# project_id = region.project.id
# site=Site.objects.filter(region_id=self.kwargs.get('pk'))
# site.update(region=None)
# region.is_active = False
# region.save()
#
# return HttpResponseRedirect(reverse('fieldsight:project-dashboard', kwargs={'pk':region.project.id}))
示例12: has_permission
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def has_permission(self, request: Request, view: View) -> bool:
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_authenticated
示例13: has_object_permission
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def has_object_permission(
self, request: Request, view: View, obj: Any
) -> bool:
if request.method in permissions.SAFE_METHODS:
return True
if not request.user.is_authenticated:
return False
return obj.author == request.user
示例14: has_object_permission
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def has_object_permission(
self, request: Request, view: View, obj: Any
) -> bool:
if request.method in permissions.SAFE_METHODS:
return True
if not request.user.is_authenticated:
return False
return obj.author == request.user
示例15: get
# 需要导入模块: from django.views import generic [as 别名]
# 或者: from django.views.generic import View [as 别名]
def get(request, slug, id_): # pylint: disable=unused-argument
"""View responsible for showing join form for particular offer."""
if request.user.is_authenticated():
has_applied = Offer.objects.filter(
volunteers=request.user,
volunteers__offer=id_,
).count()
if has_applied:
messages.error(
request,
"Już wyraziłeś chęć uczestnictwa w tej ofercie."
)
return redirect('offers_list')
offer = Offer.objects.get(id=id_)
context = {
'form': OfferApplyForm(),
'offer': offer,
'MEDIA_URL': settings.MEDIA_URL,
}
context['volunteer_user'] = UserProfile()
if request.user.is_authenticated():
context['volunteer_user'] = request.user.userprofile
return render(
request,
'offers/offer_apply.html',
context
)