1
這裏有兩種型號 - 物業和開發商:使用模式挽救了兩個相關的模型形成
class Property(models.Model):
property_type = models.CharField(max_length=255, default='Apartment')
specifications = models.CharField(max_length=255, default='Basic')
built_up_area = models.FloatField(max_length=6, null=False)
total_area = models.FloatField(null=False)
number_of_bedrooms = models.CharField(max_length=3, default=1)
number_of_bathrooms = models.CharField(max_length=3, default=1)
number_of_parking_spaces = models.CharField(max_length=2, default=0)
address_line_one = models.CharField(max_length=255, null=False)
address_line_two = models.CharField(max_length=255, default=None)
city = models.CharField(max_length=255, null=False)
state = models.CharField(max_length=255, null=False)
pin_code = models.CharField(max_length=20, null=False)
developer = models.ForeignKey('Developer')
connectivity = models.CharField(max_length=255, default=None, null=True)
neighborhood_quality = models.CharField(max_length=255, default=None, null=True)
comments = models.CharField(max_length=255, default=None, null=True)
def __unicode__(self):
return self.property_type
class Developer(models.Model):
name = models.CharField(max_length=255, null=False)
def __unicode__(self):
return self.name
這裏是它的相應的形式:
class PropertyForm(ModelForm):
developer = forms.CharField()
class Meta:
model = Property
fields = [
'built_up_area',
'total_area',
'number_of_bedrooms',
'number_of_bathrooms',
'number_of_parking_spaces',
'address_line_one',
'address_line_two',
'city',
'state',
'pin_code',
]
widgets = {
'number_of_bedrooms': forms.Select(
choices=((1, 1,), (2, 2), (3, 3)),),
'number_of_bathrooms': forms.Select(
choices=((1, 1,), (2, 2), (3, 3)),),
'number_of_parking_spaces': forms.Select(
choices=((1, 1,), (2, 2), (3, 3)),),
'developer': forms.TextInput(),
}
def __init__(self, *args, **kwargs):
super(PropertyForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.fields['address_line_two'].required = False,
self.helper.layout = Layout(
AppendedText('built_up_area', 'sq ft'),
AppendedText('total_area', 'sq ft'),
'number_of_bedrooms',
'number_of_bathrooms',
'number_of_parking_spaces',
'address_line_one',
'address_line_two',
'city',
'state',
'pin_code',
'developer',
ButtonHolder(
Submit('Submit', 'submit', css_class='btn-block')
)
)
def save(self, commit=True):
developer = self.cleaned_data['developer']
developer, created = Developer.objects.get_or_create(name=developer)
self.instance.developer = developer
return super(PropertyForm, self).save()
還有什麼更好的辦法來節省相關的對象使用單個表單?
這裏使用的是formset嗎?我讀了他們,但無法得到它。
是的,我可以肯定這樣做。這是我目前使用的解決方案,但這需要我先保存相關模型(開發人員),然後重寫項目窗體的保存方法,以將開發人員明確設置爲已保存的開發人員。我想知道django是否可以幫助解決這個問題,因爲通過相同的模型保存相關對象是相當簡單的。 – utkbansal