I am working with an ecommerce app where everone who login can post their product but I want only staff user to post the product when the staff user is true: my models.py is:
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
and my views.py for creating product is:
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)
Also I want that if staff is true then navbar show create product for user. right now if user is authenticated navbar show him to post the product
{% 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%}
You can use the UserPassesTestMixin
in your view like this.
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
And in the template you can test with this {% if request.user.is_staff %}
You should checkout the staff_member_required decorator and as already answered, use {% if user.is_staff %}
in your template for the navigation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.