如何控制在Django中可以看到哪些经过身份验证的用户?

时间:2019-04-16 03:01:41

标签: python html django authentication view

试图隐藏视图以创建餐厅老板以外的任何人。

使用示例显示了使用组并测试用户是否在该组中,但似乎没有任何效果。

views.py

def is_owner(user):
    if user.objects.filter(name="Owner").exists():
        return True

class CreateRestaurantView(generic.CreateView):
    form_class = CreateRestaurantForm
    success_url = reverse_lazy('home')
    template_name = 'signup.html'

@login_required
def create_restaurant(request):
    if is_owner == True:
        if request.method == "POST":
            form = CreateRestaurantForm(request.POST)
            if form.is_valid():
                restaurant = form.save(commit=False)
                restaurant.Restaurant_Owner = request.user
                restaurant.save()
                return redirect('restaurant_list')
        else:
            form = CreateRestaurantForm()
        return render(request, 'create_restaurant.html', {'form': form})
    else:
        return render(request, 'home.html')

forms.py

所有者的注册表格

class OwnerCreationForm(forms.ModelForm):
    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
    }
    password1 = forms.CharField(label=_("Password"),
        widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
        widget=forms.PasswordInput,
        help_text=_("Enter the same password as above, for verification."))

    class Meta:
        model = User
        fields = ("username",)

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

    def save(self, commit=True):
        user = super(OwnerCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])

        if commit:
            user.save()
            group = Group.objects.get(name='Owner')
            user.groups.add(group)

        return user

当用户属于“所有者”组但我要测试的功能(is_owner)无法正常工作并且始终为false时,我试图获取显示create_restaurant表单的视图。

1 个答案:

答案 0 :(得分:1)

首先,您将 is_owner 定义为 功能 ,因此,应将其称为 { {1}}

第二件事是,要搜索 is_owner(any_user_object) ,应为

Group

代码段

user.groups.filter(name="Owner").exists()

UPDATE-1

如下更改 def is_owner(user): return user.groups.filter(name="Owner").exists() @login_required def create_restaurant(request): if is_owner(request.user) == True: if request.method == "POST": form = CreateRestaurantForm(request.POST) if form.is_valid(): restaurant = form.save(commit=False) restaurant.Restaurant_Owner = request.user restaurant.save() return redirect('restaurant_list') else: form = CreateRestaurantForm() return render(request, 'create_restaurant.html', {'form': form}) else: return render(request, 'home.html') save() 方法

OwnerCreationForm