用户首次提交后如何使模型对象不可编辑

How to make model objects uneditable after first submission by users

我已经建立了一个配置文件模型。我也已经能够将数据渲染到模板,但是,这目前可以由登录用户编辑。

然而,我的计划是给用户一次性的访问权限,让他们自己填写数据,一旦他们提交,除了具有 is_staff 或超级管理员权限的用户外,这些数据不能被他们编辑,即使他们将在个人资料视图中看到他们的数据。

这可能吗?如果是,我可以遵循什么策略 and/or 示例,因为我完全不知道如何去做。

views.py

@transaction.atomic
def edit_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        employee_form = EmployeeProfileUpdateForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and employee_form.is_valid():
            user_form.save()
            employee_form.save()
            messages.success(request, 'Account successfully updated!')
            return render(request, 'accounts/update-profile.html')
        else:
            messages.warning(request, 'Please correct the error(s) below')
    else:
        user_form = UserForm(instance=request.user)
        employee_form = EmployeeProfileUpdateForm(instance=request.user.profile)
    return render(request, 'accounts/update-profile.html', {
        'user_form': user_form,
        'employee_form': employee_form,
    })

如果您使用 generic class based views provided by Django it's fairly simple. The mixin UserPassesTestMixin 添加一个方法 test_func 到您可以使用的视图 return TrueFalse 如果用户有是否允许

from django.views.generic import CreateView, UpdateView, DetailView
from django.contrib.auth.mixins import UserPassesTestMixin


class ProfileCreateView(CreateView):
    # Used for creation - has no special permissions
    model = Profile


class ProfileDetailView(DetailView):
    # Used for viewing - has no special permissions
    model = Profile


class ProfileUpdateView(UserPassesTestMixin, UpdateView):
    # Used for updating - requires a user be superuser or staff
    model = Profile

    def test_func(self):
        return self.request.user.is_superuser or self.request.user.is_staff