我有2个模型如下:
class Types_of_Expenditures(models.Model):
Expenditure_owner = models.CharField(default="None",max_length=50)
Expenditure_Type = models.CharField(default="Miscellaneous",max_length=50)
Expenditure_Type_Description = models.CharField(max_length=200)
def __unicode__(self):
return self.Expenditure_Type
class Expenditure(models.Model):
exp_owner= models.CharField(default='None',max_length=50)
exp_date = models.DateTimeField("Expenditure_Date")
description = models.CharField(max_length=1000)
amount = models.FloatField(default=0)
currency = models.CharField(max_length=15,default="MYR",editable=True)
exp_pocket = models.ForeignKey(Pockets, null=True, blank=True)
exp_type = models.ForeignKey(Types_of_Expenditures)
class Meta:
unique_together = ('exp_date', 'description',)
def __unicode__(self):
return self.description
对于以上 2 种模型,我使用以下 2 种形式:
class Types_of_Expenditures_Form(forms.ModelForm):
class Meta:
model = Types_of_Expenditures
class ExpenditureDeleteForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ExpenditureDeleteForm, self).__init__(*args, **kwargs)
self.fields['exp_pocket'].widget = forms.TextInput(attrs={'readonly':'readonly'})
self.fields['exp_type'].widget = forms.TextInput(attrs={'readonly':'readonly'})
self.fields['amount'].widget = forms.TextInput(attrs={'readonly':'readonly'})
for f in self.fields:
self.fields[f].widget.attrs['readonly'] = "readonly"
class Meta:
model = Expenditure
exclude = ['exp_owner','currency']
fields = ['exp_date', 'description', 'exp_type', 'amount','exp_pocket']
在我看来,我这样称呼它:
ExpDeleteFormSet = modelformset_factory(Expenditure,extra=0,
can_delete=True,fields = ['exp_date', 'description', 'exp_type', 'amount','exp_pocket'],form=ExpenditureDeleteForm)
formset = ExpDeleteFormSet(queryset=Expenditure.objects.filter(exp_owner=str(request.user)))
return render_to_response('expenditure.html', {'formset':formset}, context)
现在呈现的表单集如下图所示:
问题/问题: 如图所示,类型编号为 1 或 2 。这 1 在 Types_of_Expenditure 中具有作为 Miscellaneous 的相应值,而 2 具有其他值,依此类推。是否可以将类型显示为 Types_of_Expenditure 的相应值?
我尝试了各种方法,例如使用 Baseformset 尝试使用查询集但无法找出如何去做?
什么尝试
使用 inlineformset_factory 如下,但这样做不会渲染模板中的任何内容:
ExpDeleteFormSet = inlineformset_factory(Types_of_Expenditures, Expenditure, fk_name="exp_type", fields = ['exp_date', 'description', 'exp_type', 'amount','exp_pocket'], can_delete=True,form=ExpenditureDeleteForm)
效果很好 的替代方法:我现在使用的替代方法是将 Expenditure_Type 本身作为主键,但是我仍然在寻找原始问题的答案:
Expenditure_Type = models.CharField(primary_key=True,max_length=50)