Thursday, December 9, 2021

Restrict django choice field according to user

i have two users with two different permissions user a can create and close where usertype b can accept and complete i have to restrict the choice fields according to the user i am getting the error 

models.py

class Ticket(models.Model):
ticket_title = models.CharField(max_length=200)
ticket_description = models.TextField()
created_by = models.ForeignKey(User,related_name = 'created_by',blank=True,null=True,on_delete=models.CASCADE)

STATUS_CHOICES = (
('Opened','Opened'),
('Accepted','Accepted'),
('Completed','Completed'),
('Closed','Closed')
)

status = models.CharField('Status',choices=STATUS_CHOICES,max_length = 100,default = 'Opened')

accepted_by = models.ForeignKey(User,related_name='assigned_to',on_delete=models.CASCADE,blank=True,null=True)



def __str__(self):
return self.ticket_title


forms.py

class TicketEditForm(forms.ModelForm):
class Meta:
model = Ticket
fields = ('ticket_title', 'ticket_description','status')


def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['request'] = self.request.user
return kwargs


def __init__(self, *args, **kwargs):

usertype = kwargs.pop('request')
super().__init__(args, **kwargs)
if usertype.is_manager == True:
self.fields['status'].choices = (
('Closed','Closed'),
)
else:
self.fields['status'].choices = (
('Accepted','Accepted'),
('Completed','Completed'),
)



views.py

class DeveloperEditTicketView(LoginRequiredMixin,UpdateView):
template_name = 'app/edit_ticket.html'
model = Ticket
form_class = TicketEditForm
context_object_name = 'tickets'
success_url = reverse_lazy('dev_dashboard')


def form_valid(self,form):
ticket = form.instance
ticket.accepted_by = self.request.user
ticket.save()
return super().form_valid(form)

I am getting error as below


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ec5f0c82-7a7b-441d-8a2d-858ce5dc41edn%40googlegroups.com.

No comments:

Post a Comment