本文介绍了Django访问ModelForm中的实例数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ModelForm中,如何仅使用与当前实例相关的值过滤选择窗口小部件内容? (称为ModelForm的实例)



例如:

  class smsForm(ModelForm):

class Meta:
model = SMS
fields = ['phone','state']
widgets = {
'phone':select(choices = phoneSMS.objects.all()。values_list('id','phone'),attrs = {'class':'form-control',}),
'state' :bootStrapButtonSelect(attrs = {'class':'buttons-sms',}),}

我想做的是使用仅包含短信参考的手机过滤该phoneSMS。以下是模型:

  class SMS(models.Model):
student = models.ForeignKey(Student)
day = models.DateField(db_index = True)
attempts = models.IntegerField(default = 0)
phone = models.CharField(max_length = 9,default ='---')
sent = models.BooleanField(default = False)
state = models.CharField(max_length = 20,choices = OPTIONS,default =nothing)



class phoneSMS(models.Model):
phone = models.CharField(max_length = 120)
sms = models.ForeignKey(SMS)
/ pre>

我尝试使用 objects.filter(sms = SMS)但没有结果。

解决方案

在声明的那一刻,你没有关于模型实例的信息,ModelForm将被初始化。



在模型实例已经知道的情况下,您必须动态设置选项,而且它不会早于 __ init __()方法:

  class SmsForm(ModelForm):

class Meta:
model = SMS
fields = ['phone','state']
widgets = {
'phone':Select(attrs = {'class':'form-control',}),
'state':bootStrapButtonSelect(attrs = {'class' sms',})
}

def __init __(self,* args,** kwargs):
super(SmsForm,self).__ init __(* args ** kwargs)

self.fields ['phone']。widget.choices = \
phoneSMS.objects.filter(sms = self.instance.sms)\
.values_list 'id','phone')

仍然要小心,因为没有人保证self.instance设置为 - 这取决于可选实例参数。所以更好地附上适当的条件和处理这种情况的方法。


In a ModelForm, how can I filter a Select widget content with only values related with current instance? (The instance which called the ModelForm)

For example:

class smsForm(ModelForm):

    class Meta:
        model = SMS
        fields = ['phone', 'state']
        widgets = {
            'phone': Select(choices=phoneSMS.objects.all().values_list('id', 'phone'), attrs={'class':'form-control',}),
            'state': bootStrapButtonSelect( attrs={'class': 'buttons-sms', }), }

What I want to do is to filter that phoneSMS with only the phones which contains the sms reference. Here're the models:

class SMS(models.Model):
    student = models.ForeignKey(Student)
    day = models.DateField(db_index=True)
    tries = models.IntegerField(default=0)
    phone = models.CharField(max_length=9, default='---')
    sent = models.BooleanField(default=False)
    state = models.CharField(max_length=20, choices=OPTIONS, default='nothing')



class phoneSMS(models.Model):
    phone= models.CharField(max_length=120)
    sms = models.ForeignKey(SMS)

I tried with objects.filter(sms=SMS) but no result.

解决方案

In the moment of declaration you have no information about model instance ModelForm will be initialized with.

You have to dynamically set choices when model instance is already known and it happens not earlier than in __init__() method:

class SmsForm(ModelForm):

    class Meta:
        model = SMS
        fields = ['phone', 'state']
        widgets = {
            'phone': Select(attrs={'class':'form-control',}),
            'state': bootStrapButtonSelect( attrs={'class': 'buttons-sms', })
        }

    def __init__(self, *args, **kwargs):
        super(SmsForm, self).__init__(*args **kwargs)

        self.fields['phone'].widget.choices = \
             phoneSMS.objects.filter(sms=self.instance.sms) \
                             .values_list('id', 'phone')

Still be careful as nobody guaranties that self.instance is set - it depends on optional instance argument. So better attach proper conditions and way of handling such case.

这篇关于Django访问ModelForm中的实例数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 17:14