以django形式动态添加字段

时间:2018-03-08 10:11:56

标签: django django-models django-forms

Image of the form

在“服务提供”字段中,当用户想要添加多个服务名称时,我想动态添加更多文本框。如何实现?

models.py

    from django.db import models
    from django.contrib.auth.models import User

    class CustomerProfile(models.Model):
        customer_username = models.ForeignKey('auth.User')
        first_name = models.CharField(max_length=20)
        last_name = models.CharField(max_length=20)
        organisation_name = models.CharField(max_length=20)
        website = models.URLField()
        office_address = models.CharField(max_length=200)
        service_provided = models.CharField(max_length=100)
        contact = models.IntegerField()
        city = models.CharField(max_length=20)
        state = models.CharField(max_length=20)
        zip_code = models.IntegerField()
        number_of_employee = models.IntegerField()
        establishment_year = models.IntegerField()
        number_of_project_done = models.IntegerField()

        def __str__(self):
            return self.organisation_name

forms.py

    from django import forms
    from .models import CustomerProfile

    class CustomerProfileForm(forms.ModelForm):

        class Meta:
            model = CustomerProfile
            fields = '__all__'
            exclude = ('customer_username',)

1 个答案:

答案 0 :(得分:2)

您可以在表单类的init覆盖中动态添加字段。

init方法的示例(在表单类中放置类似的东西):

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

    self.fields['test_field'] = forms.CharField(max_length=250)

如果您想在页面上添加更多字段而不重新加载,则必须使用其他解决方案。