简体   繁体   English

将表单外键限制为相关模型中的选择

[英]Limit forms foreign key to a choices in related model

I am working on creating a form but stuck at this issue.我正在创建一个表单,但卡在这个问题上。

I have several businesses in the Business Model.我在商业模式中有几项业务。 Each Business has its own Service in Services Model.每个企业都有自己的服务中的服务模型。 The User is tied to only one Business.用户仅与一项业务相关联。 Both Business, Service have a relationship.两者业务,服务都有关系。

My Challenge我的挑战

I have a Service Request Form.我有一份服务申请表。 When I present this Service Request Model Form, I want to show only services for One Business, that the customer/user belongs to.当我展示此服务请求模型表时,我只想显示客户/用户所属的 One Business 的服务。 Please help me how this is possible.请帮助我这怎么可能。 I thought it would be like "Instance = Business".我认为它会像“实例 = 业务”。 I understood its not that simple.我明白它不是那么简单。

For example: Business1 has "Cars" and "Motor Bikes" as Services and Business2 has "nails" and "Hair Spa" as services.例如:Business1 将“Cars”和“Motor Bikes”作为服务,Business2 将“指甲”和“Hair Spa”作为服务。 If a user from Business1 logged in and opened Service Request Form, She/He should see only "Cars" and "Motor Bikes" in service selection drop down.如果来自 Business1 的用户登录并打开服务请求表,她/他应该在服务选择下拉列表中只看到“汽车”和“摩托车”。

''' '''

    # class Service(models.Model):
class Business(models.Model):
    name = models.CharField(max_length=25)
    description = models.CharField(max_length=100)
    active = models.BooleanField(default=True)

class BusinessUser(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='business')
    
class Services(models.Model):   
    business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='business_services')
    name = models.CharField(max_length=15)
    active = models.BooleanField(default=True)

class ServiceRequest(models.Model):
    business = models.ForeignKey(Business, on_delete=models.DO_NOTHING)
    service = models.ForeignKey(Service, on_delete=models.DO_NOTHING, blank=True)
    requester_name = models.CharField(max_length=15)

 class  ServiceRequestForm(forms.ModelForm):
     class Meta:
        model = ServiceRequest
        fields = '__all__'

def newServiceRequest(request):  //the view
    if request.method == 'GET':
        user = request.user
        business = user.business
        serviceRequestForm = ServiceRequestForm(instance=business)
        return render(request,'service.html', {'form':serviceRequestForm})

''' '''

One way is to use django-select2 .一种方法是使用django-select2 See installation instructions here 请参阅此处的安装说明

Then in your form you can do:然后在您的表单中,您可以执行以下操作:

 class  ServiceRequestForm(forms.ModelForm):
     class Meta:
        model = ServiceRequest
        fields = '__all__'
        widgets = {
            'business': ModelSelect2Widget(
                    model=Business,
                    attrs={'class': 'form-control', 'data-minimum-input-length': 0},
                    search_fields=['name__icontains'],
            ),
            'service': ModelSelect2Widget(
                    model=Services,
                    attrs={'class': 'form-control', 'data-minimum-input-length': 0},
                    search_fields=['name__icontains'],
                    dependent_fields={'business': 'business'},
            ),
        }

The key element is the dependent_fields option.关键元素是dependent_fields选项。 Read more about it here 在此处阅读更多相关信息

You can pass the current business and update your queryset in the ModelForm constructor.您可以通过当前的业务和更新querysetModelForm构造。



class  ServiceRequestForm(forms.ModelForm):

    def __init__(self, business, *args, **kw):
        super(ServiceRequestForm, self).__init__(*args, **kw)
        self.fields['business'].queryset = \
           self.fields['business'].queryset.filter(pk=business.pk)

    class Meta:
        model = ServiceRequest
        fields = '__all__'


def newServiceRequest(request):  # the view
    user = request.user
    business = user.business
    
    if request.method == 'POST':
        serviceRequestForm = ServiceRequestForm(business, data=request.POST)
        if (serviceRequestForm.is_valid()):
             serviceRequest = serviceRequestForm.save()
             # another stuff...
             # ... 
    else:
        serviceRequestForm = ServiceRequestForm(business)

    return render(request,'service.html', {'form':serviceRequestForm})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM