2010-04-08 34 views
20

Làm cách nào để thêm trường trong hàm init của biểu mẫu? ví dụ. trong mã bên dưới, tôi muốn thêm một trường tiểu sử.tạo biểu mẫu django trên init

class StaffForm(forms.ModelForm): 
    def __init__(self, user, *args, **kwargs): 
     if user.pk == 1: 
      self.fields['profile'] = forms.CharField(max_length=200) 

     super(StaffForm, self).__init__(*args, **kwargs) 

    class Meta: 
     model = Staff 

Tôi biết tôi có thể thêm nó ngay dưới lớp StaffForm .... dòng nhưng tôi muốn đây là động tùy thuộc vào những gì người dùng được thông qua năm nên không thể làm theo cách này.

Cảm ơn

+3

* Có thể lặp lại của một số trong những: * http://stackoverflow.com/search?q=django+dynamic+form, đặc biệt là http://stackoverflow.com/questions/2390000/dynamic-django- các trường biến dạng và http://stackoverflow.com/questions/2506136/storing-dynamic-fields-in-django-forms –

+0

được sao chép: https://stackoverflow.com/questions/22390416/setting-initial-django- phương thức form-field-value-in-the-init –

Trả lời

33

Chỉ cần chuyển vòng chức năng init sao cho siêu được gọi trước khi thêm các trường khác.

class StaffForm(forms.ModelForm): 
    def __init__(self, user, *args, **kwargs): 
     super(StaffForm, self).__init__(*args, **kwargs) 

     if user.pk == 1: 
      self.fields['profile'] = forms.CharField(max_length=200) 
      self.fields['profile'].initial = 'whatever you want' 
    class Meta: 
     model = Staff 
Các vấn đề liên quan