只有员工用户可以在django中发布产品



我正在使用一个电子商务应用程序,其中每个人登录可以发布他们的产品,但我只希望员工用户在员工用户为真时发布产品:我的models.py是:

class User(AbstractBaseUser):
email = models.EmailField(max_length=255 ,unique=True)
full_name = models.CharField(max_length=255, blank=True, null=True)
active = models.BooleanField(default=True)  #can login
staff = models.BooleanField(default=False)  #staff user non super user
admin = models.BooleanField(default=False)  #superuser
time_stamp = models.DateTimeField(auto_now_add=True)
#USERNAME_FIELD and password are required by default
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
object = UserManager()
def __str__(self):
return self.email
def get_full_name(self):
if self.full_name:
return self.full_name
return self.email
def get_short_name(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self , app_label):
return True
@property
def is_staff(self):
return self.staff
@property
def is_admin(self):
return self.admin
@property
def is_active(self):
return self.active

和my views.py用于创建产品是:

class ProductCreateView(LoginRequiredMixin,CreateView):
model = Product
template_name = 'product-form.html'
fields = ['title', 'price' , 'status' , 'size' , 'color', 'image' , 'description']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)

我还希望,如果员工是真的,然后导航栏显示创建产品为用户。现在,如果用户通过了身份验证,导航栏显示他发布产品

{% if request.user.is_authenticated %}
<li class="nav-item {% if request.path == logout_url%}active{% endif %}">
<a class="nav-link" href="{{ logout_url }}">Logout</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'profile'%}">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'products:product-create'%}">Create Product</a>
</li>
{% else%}

您可以在视图中这样使用UserPassesTestMixin

class ProductCreateView(UserPassesTestMixin,CreateView):
model = Product
template_name = 'product-form.html'
fields = ['title', 'price' , 'status' , 'size' , 'color', 'image' , 'description']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
return self.request.user.is_staff

在模板中你可以用这个{% if request.user.is_staff %}

来测试

您应该检查staff_member_required装饰器,并且已经回答了,在您的模板中使用{% if user.is_staff %}作为导航。

相关内容

  • 没有找到相关文章

最新更新