The knight
The knight

Reputation: 137

Dynamically add field to a form python django

I want to have a Django form in which a user can add multiple stop_name,stop_longitude,stop_latitude using the Add more button inside. Let's suppose a user has 3 stop_names so he will have to click on the Add more twice. And on each add more above fields will populate again. I am new to Django so I need some help.

This is my model

class SupplyChainStops(models.Model):
    ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE)
    stop_name = ArrayField(models.CharField(max_length=1024, null=True, blank=True))
    stop_longitude = ArrayField(models.CharField(max_length=500, null=True, blank=True))
    stop_latitude = ArrayField(models.CharField(max_length=500, null=True, blank=True))

Upvotes: 2

Views: 2171

Answers (1)

Godda
Godda

Reputation: 1001

Okey using formset factory i very straight forward and simple to render multiple fields for user to fill in their information. First of all you would need to create forms.py in your project and then import django's formset_factory in forms. We would do something like so:

from django.forms import formset_factory
from .models import SupplyChainStops

# Here we are creating a formset to handle the maniplations of our form to
# have extra field by using the extra parameter to formset_factory
# and also we can add a delete function to allow users to be able to delete 

Formset = formset_factory(SupplyChainStops, fields=[' stop_name',' stop_longitude','stop_latitude'], extra=4, can_delete=True)
# I have set the formset to give us an extra field of four and enable users 
# to delete 

Now we are going to work on the view to handle our formset.

from django.views.generic.edit import FormView
from .forms import Formset

class formsetView( FormView):
      template_name = 'formset.html'
      form_class = Formset
      success_url = '/'
      
      

In our template we will do something like this .


<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Add">
</form>

Doing this in a function base view

from .forms import Formset

def formset_view(request):
    if request.method == 'POST':
       formset = Formset(request.POST,)
       if formset.is_valid():
          formset.save()
    else:
          formset = ()
    return render (request, 'formset.html',{'formset':formset})

In your HTML Template

<form method="post">{% csrf_token %}
    {{ formset.as_p }}
    <input type="submit" value="Add">
</form>

Upvotes: 2

Related Questions