python - 创建一个无法保存到数据库的 Django 演示用户

标签 python django

我正在创建一个 Django Web 应用程序,用户可以在其中免费创建帐户。我还设置了一个演示用户,该用户已配置并且已将数据附加到其帐户。此演示帐户的目的是让新用户快速了解应用程序的功能。

现在我想让这个演示用户访问我的所有 View ,但在用户保存表单时不保存到数据库。

当然,我知道有多种方法可以做到这一点。但它们都要求我编辑多个页面或 View :

  • 保存表单时检查是否是演示用户,如果是:不保存
  • 当演示用户登录时,从我的模板中删除保存按钮

有没有更简单/更干净的解决方案来做到这一点?如何以特定用户永远无法保存到数据库的方式设置我的应用程序?

我使用的解决方案

marcusshep 的想法为我提供了一个解决方案。我为页面创建了以下 View ,在点击保存按钮时应加载表单但不保存表单。直到现在我还无法做到这一点。此时下面的页面会立即渲染出303

class FormViewOPRadio(FormView):
def dispatch(self, request, *args, **kwargs):
    # Return 403 for demo user
    temp = 'temp'
    if self.request.user.email == 'demo@opradio.nl':
        raise PermissionDenied
    else:
        return super(FormViewOPRadio, self).dispatch(request, *args, **kwargs)


class UpdateViewOPRadio(UpdateView):
def dispatch(self, request, *args, **kwargs):
    # Return 403 for demo user
    temp = 'temp'
    if self.request.user.email == 'demo@opradio.nl':
        raise PermissionDenied
    else:
        return super(UpdateViewOPRadio, self).dispatch(request, *args, **kwargs)


class DeleteViewOPRadio(DeleteView):
def dispatch(self, request, *args, **kwargs):
    # Return 403 for demo user
    temp = 'temp'
    if self.request.user.email == 'demo@opradio.nl':
        raise PermissionDenied
    else:
        return super(DeleteViewOPRadio, self).dispatch(request, *args, **kwargs)

此外,还有一些我使用过的页面应该无法访问

from braces.views import UserPassesTestMixin

class UserNotDemoUser(UserPassesTestMixin):
raise_exception = True

def test_func(self, user):
    return user.email != 'demo@opradio.nl'

我尝试过的

我为页面创建了以下 View ,在点击保存按钮时应加载表单但不保存表单

class FormViewOPRadio(FormView):
def form_valid(self, form):
    # Return 403 for demo user
    if self.request.user.email == 'demo@opradio.nl':
        raise PermissionDenied
    else:
        return super(FormViewOPRadio, self).form_valid(form)

class AddStream(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, FormViewOPRadio):
"""Is the page used to add a Stream"""
template_name = 'opradioapp/addoreditstream.html'
form_class = AddStreamForm
success_url = reverse_lazy('opradioapp_home')
success_message = "De stream is opgeslagen"

# Validate if the user is the maintainer of the station
def test_func(self):
    user = self.request.user
    mainuserstation = MainUserStation.objects.get(slugname=self.kwargs['mainuserstationslug'])
    if mainuserstation.maintainer == user:
        return True
    else:
        return False

def form_valid(self, form):
    user = self.request.user
    mainuserstation = MainUserStation.objects.get(slugname=self.kwargs['mainuserstationslug'])
    userstream = UserStream()
    userstream.mainuserstation = mainuserstation
    userstream.name = form.cleaned_data['name']
    userstream.slugname = 'temp'
    userstream.description = form.cleaned_data['description']
    userstream.save()

    member = Member.objects.get(user=user, mainuserstation=mainuserstation)
    member.streamavailable.add(userstream)
    member.save()
    return super(AddStream, self).form_valid(form)

这样做时

        if self.request.user.email == 'demo@opradio.nl':
        raise PermissionDenied

在 save() 调用之后调用。我怎样才能改变这个?我之前尝试过调用 super 但遇到了问题。

最佳答案

Off course there are multiple ways of doing this that I know of. But they all require me to edit multiple pages or views:

好吧,如果您使用某些DRY,则不必为每个模板或 View 重复逻辑。 Python 和 Django 的功能。

Class Based View Inheritance

class CheckForDemoUser(View):
    def dispatch(self, request, *args, **kwargs):
        # check for demo user
        # handle which ever way you see fit.
        super(CheckForDemoUser, self).dispatch(request, *a, **kw)

class ChildClass(CheckForDemoUser): # notice inheritance here
    def get(request, *args, **kwargs):
        # continue with normal request handling
        # this view will always check for demo user
        # without the need to repeat yourself.

Function Decorators

def check_for_demo_user(func):
   def func_wrapper(request, *args, **kwargs):
       # implement logic to determine what the view should
       # do if the request.user is demo user.
   return func_wrapper


@check_for_demo_user
def my_view(request, *args, **kwargs):
    # automatic checking happening before view gets to this point.

Inclusion Tags您可以将隐藏/显示表单提交按钮的逻辑隔离在一处,并在演示用户所在的多个页面中引用您的自定义标记。

这些只是实现此逻辑的一些方法,而无需一遍又一遍地重复。

关于python - 创建一个无法保存到数据库的 Django 演示用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38696423/

相关文章:

python - BeautifulSoup 刮img

python - matplotlib 中具有 N 个不同颜色阴影的条形图

python - 如何使用假设库创建日期时间索引 pandas DataFrame?

django - 使用参数创建 django 管理器

Django表单字段中的字符串列表

python - 使用 Twython 将多个用户 ID 转换为用户名

python - angularjs 最快/最简单的后端?

javascript - 自定义选择标签功能

python - 我应该在这里使用 HttpResponseRedirect 吗?

python - 在 python 中映射一组值