1

Image of the form

In the Service Provided field, I want to add more text box dynamically,when the user wants to add more than one service name. How to achieve that?

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',)
6
  • Use Django formset_factory OR more suitable in your case JQuery / Javascript to add more forms. Commented Mar 8, 2018 at 10:22
  • Your model allows each CustomerProfile to have a single service. If you want to allow multiple services for each profile, you'll need to rethink your models (e.g. have a Service model with a foreign key to CustomerProfile. Commented Mar 8, 2018 at 10:22
  • .My objective is that user can add service by clicking on plus button, without reloading the page. Can you pls provide some code for that @Alasdair Commented Mar 8, 2018 at 10:29
  • No, I can't write that code for you. Even if you write that code, your current model only allows one service to be stored for each profile. My point is that you should fix your model before you go any further. Commented Mar 8, 2018 at 10:32
  • ok got it. Thanks for the help@Alasdair Commented Mar 8, 2018 at 10:34

1 Answer 1

3

You can dynamically add fields in the init override of your form class.

Example of the init method (put something like this in your form class):

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

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

You have to use other solutions if you want to add more fields on the page itself without reloads.

Sign up to request clarification or add additional context in comments.

Comments