Reputation: 17
I'm trying to do a crud in Django, it's about jefe and encargados. When I am logged in as an administrator, it has to allow me to create a encargados, but not a manager, but if I log in as a manager, it has to allow me to create a new encargados. For the jefe I am using a table called users and for the admin I am using the one from the Django admin panel.
Here are the models:
roles = (
('encargado', 'ENCARGADO'),
('jefe','JEFE'),
)
class Usuarios(models.Model):
id = models.BigAutoField(primary_key=True)
nombre = models.CharField(max_length=30)
rol = models.CharField(max_length=30, choices=roles, default='encargado')
correo = models.CharField(max_length=30)
contraseña = models.CharField(max_length=30)
cedula = models.CharField(max_length=30)
class Meta:
db_table = 'usuarios'
This is the create view
class UsuarioCrear(SuccessMessageMixin, CreateView):
model = Usuarios
form = Usuarios
fields = "__all__"
success_message = 'usuario creado correctamente !'
def get_success_url(self):
return reverse('leer')
This would be the html to create, here I put a restriction that the roles are only seen as administrator. but really what is necessary is that if I am as an administrator it only lets me select the jefe and if I am as a jefe it only lets me select encargados
{% csrf_token %}
<!-- {{ form.as_p }} -->
<div class="form-group">
<label for="id" class="txt_negrita">Id</label>
{{ form.id|add_class:"form-control" }}
</div>
<div class="form-group">
<label for="nombre" class="txt_negrita">Nombre</label>
{{ form.nombre|add_class:"form-control" }}
</div>
{% if user.is_superuser %}
<div class="form-group">
<label for="rol" class="txt_negrita">Rol</label>
{{ form.rol|add_class:"form-control"}}
</div>
{%endif%}
<div class="form-group">
<label for="correo" class="txt_negrita">Correo</label>
{{ form.correo|add_class:"form-control" }}
</div>
<div class="form-group">
<label for="contraseña" class="txt_negrita">Contraseña</label>
{{ form.contraseña|add_class:"form-control" }}
</div>
<div class="form-group">
<label for="cedula" class="txt_negrita">Cedula</label>
{{ form.cedula|add_class:"form-control" }}
</div>
<button type="submit" class="btn btn-primary">Aceptar</button>
<a href="../" type="submit" class="btn btn-danger">Cancelar</a>
</form>
Upvotes: 0
Views: 45
Reputation: 5267
In your view, you need to get the user so you can pass it to the form via kwargs. Add the following method to your view
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
Now in your form you can test against the user when you initialise the form
class Usuarios(forms.Form):
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
#use whatever method you need to determine options,
# if self.user.is_staff: etc
if self.user.rol == 'jefe':
self.fields['rol'].choices = ('encargado', 'ENCARGADO'),
else:
self.fields['rol'].choices = ('jefe', 'JEFE'),
Upvotes: 1