Categories
Python Answers

How to dynamically add field to a form with Python Django?

To dynamically add field to a form with Python Django, we can add the form with a for loop.

For instance, we write

class MyForm(forms.Form):
    original_field = forms.CharField()
    extra_field_count = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        extra_fields = kwargs.pop('extra', 0)

        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['extra_field_count'].initial = extra_fields

        for index in range(int(extra_fields)):
            self.fields['extra_field_{index}'.format(index=index)] = \
                forms.CharField()

to create the MyForm form that has a for loop in the __init__ method that creates CharFields and add them into the self.fields dictionary dynamically.

Then in our view, we can use the form with

def myview(request):
    if request.method == 'POST':
        form = MyForm(request.POST, extra=request.POST.get('extra_field_count'))
        if form.is_valid():
            print "valid!"
    else:
        form = MyForm()
    return render(request, "template", { 'form': form })

We set the extra argument to a list we get from request.POST.get.

Then we render the template for the view with

<form>
    <div id="forms">
        {{ form.as_p }}
    </div>
    <button id="add-another">add another</button>
    <input type="submit" />
</form>
Categories
Python Answers

How to create a dynamic choice field with Python Django?

To create a dynamic choice field with Python Django, we can set the fields to a queryset value.

For instance, we write

class WaypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ChoiceField(
            choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        )

to create the WaypointForm form.

In the __init__ method, we set self.fields['waypoints'] to a ChoiceField.

And we populate the choices by setting the choices argument to a list of values that we get from the Waypoint.objects.filter(user=user) queryset.

Categories
Python Answers

How to access a dictionary element in a Python Django template?

To access a dictionary element in a Python Django template, we can use the items property.

For instance, if we have

choices = {'key1':'val1', 'key2':'val2'}

Then we can loop through the choices entries with

<ul>
{% for key, value in choices.items %} 
  <li>{{key}} - {{value}}</li>
{% endfor %}
</ul>

We get the key and value pairs from choices.items and then we render them in the li element.

Categories
Python Answers

How to iterate over model instance field names and values in template with Django Python?

To iterate over model instance field names and values in template with Django Python, we can use a queryset serializer.

For instance, we write

from django.core import serializers
data = serializers.serialize( "python", SomeModel.objects.all() )

to serialize the queryset results with serializers.serialize.

And then in our template, we write

{% for instance in data %}
    {% for field, value in instance.fields.items %}
        {{ field }}: {{ value }}
    {% endfor %}
{% endfor %}

to loop through the data list and get the values from instance.fields.items.

Categories
Python Answers

How to set default form values with Django Python?

To set default form values with Django Python, we create the form instance with the default values in the constructor arguments.

Or we can put the default values in the form definition.

For instance, we write

form = JournalForm(initial={'tank': 123})

to create a JournalForm instance with the initial argument set to a dictionary with the initial form values.

In the form definition, we can add a field with its default value by writing

tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

to set the initial value using the field constructor with the initial argument set.