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.

Categories
Python Answers

How to fix no module named MySQLdb error with Python Django?

To fix no module named MySQLdb error with Python Django, we install the mysql-python package.

To do this, we run one of:

  1. easy_install mysql-python (any OS)
  2. pip install mysql-python (any OS/ Python 2)
  3. pip install mysqlclient (any OS/ Python 3)
  4. apt-get install python-mysqldb (Ubuntu, etc.)
  5. cd /usr/ports/databases/py-MySQLdb && make install clean (FreeBSD)
  6. yum install MySQL-python (Fedora, CentOS, etc.)

to install the mysql-python package.