Tôi đang tạo một mẫu hồ sơ ở Django. Có rất nhiều trường cấu hình phụ tùy chọn nhưng tôi chỉ muốn hiển thị hai trường cùng một lúc. Làm cách nào để ẩn hoặc xóa các trường mà tôi không muốn hiển thị động?Làm thế nào để bạn tự động ẩn các trường biểu mẫu trong Django?
Dưới đây là những gì tôi có cho đến nay:
class UserProfileForm(forms.ModelForm):
extra_fields = ('field1', 'field2', 'field3')
extra_field_total = 2
class Meta:
model = UserProfile
def __init__(self, *args, **kwargs):
extra_field_count = 0
for key, field in self.base_fields.iteritems():
if key in self.extra_fields:
if extra_field_count < self.extra_field_total:
extra_field_count += 1
else:
# do something here to hide or remove field
super(UserProfileForm, self).__init__(*args, **kwargs)
Câu trả lời liên quan: http://stackoverflow.com/a/1914812/462865 –