根据登录用户以django形式过滤下拉选项

时间:2018-08-20 22:13:38

标签: django django-forms

我有一个django表单来创建名为<number> ::= <digit><number> | <digit> 的类的新实例(记录)。用户可以来自不同的Ticket,因此我需要将下拉菜单中显示的选项基本上限制为已登录用户的客户端。 clients是我在client中定义的类的属性,该类定义了admin.py的{​​{1}}名称。我知道自己走在正确的道路上,但是我很难做到这一点,因为我需要提取登录client的{​​{1}}并用它来过滤字段(例如user)在初始化表单时,将有什么帮助?请考虑我有多个应该过滤的字段,因此,如果有一种方法可以对所有字段都执行一次,那就太好了:

models.py

client

views.py

User

admin.py

business

forms.py

class Business(models.Model):
    client=models.ForeignKey('Client',on_delete=models.CASCADE, limit_choices_to={'is_active':True},)
    name=models.CharField(max_length=30,blank=False, unique=True,)
    description = models.CharField(max_length=50, blank=True, )
    is_active=models.BooleanField(default=True,)



class Ticket(MMRequestAttributes):    
    no=models.CharField('Ticket Number',max_length=50,default=uuid.uuid4,null=False, blank=False, editable=False, unique=True)
    subject=models.CharField('Subject',max_length=100,null=False, blank=False)
    business=models.ForeignKey('Business', on_delete=models.CASCADE,limit_choices_to={'is_active':True},)

    class Meta:
        permissions=(('view_ticket','Can see tickets'),)

new-ticket.html

def new_ticket(request):
    form=NewTicket(request.user)
    return render(request,'mmrapp/new_ticket.html',{'form':form})

1 个答案:

答案 0 :(得分:1)

您的操作方式正确,只需将__init__更改为此

class NewTicket(forms.ModelForm):

    def __init__(self,user, *args, **kwargs):
        super(NewTicket, self).__init__(*args, **kwargs)
        try:
            client_id = UserExtend.objects.values_list('client_id', flat=True).get(user=user)
            self.fields['business'].queryset=Business.objects.filter(client__id=client_id)
        except UserExtend.DoesNotExist:
            ### there is not userextend corresponding to this user, do what you want 
            pass


    class Meta:
        model=Ticket
        fields = ('subject','business')

也请不要忘记将request.user传递到您视图中的表单。