Drop Down Menu in Django Forms not working.

91 views
Skip to first unread message

Arun S

unread,
Aug 4, 2017, 1:07:24 PM8/4/17
to Django users
Hi,

I am trying to have a drop down menu for a field in my form but seems like its not working as required.

This is my form: forms.py

eval_states = [
        ('ACTIVE',EvalState.objects.filter(name='ACTIVE')),
        ('INACTIVE',EvalState.objects.filter(name='INACTIVE')),
        ('DELETE',EvalState.objects.filter(name='DELETE')),
        ]

class EvalForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(EvalForm, self).__init__(*args, **kwargs)
        self.fields['name'].queryset = EvalState.objects.filter(
                Q(name = 'ACTIVE') | Q(name = 'INACTIVE') | Q(name = 'DELETE'))

    class Meta:
        model = EvalState
        fields = ('name',)

my html : abc.html

    <form name="eval_form" method="post" action="#">{% csrf_token %}
        <table class="pairs">
            <tr>
                <th>Eval State:</th>
                <td>
                    {{ eval_form.name }}
                    <input type="submit" value="Save">
                </td>
            </tr>
        </table>
    </form>

view.py
    eval_form = None
    eval_form = atlas_forms.EvalForm(request.POST, EvalState)
    if eval_form.is_valid():
        print eval_form.errors
        eval_form.save()
    else:
        print eval_form.errors


What am i missing?
Basically requirement is that, i would need a drop down in the HTML and whenever the Value is set and saved, I want it to be updated in the DB.
But i am not able to get through the first step of getting the options in the HTML.

Any Help on this would be great.

Thanks
cheers
Arun.

lemme smash

unread,
Aug 5, 2017, 2:42:26 PM8/5/17
to Django users
name is a ForeignKey field? If not, you shouldn't use queryset attribute there. Use choices instead.
If you want to render all available choices from db, you can get it like Model.objects.filter(...).values_list('name', flat=True)

Arun S

unread,
Aug 5, 2017, 10:22:21 PM8/5/17
to Django users
Yes, name is a foreign key here.

lemme smash

unread,
Aug 6, 2017, 10:18:11 AM8/6/17
to Django users
so, you can maybe show you models structure here?
also, if it is a ForeignKey, why you trying to filter qs by string values? I mean Q(name = 'ACTIVE')
it's shouldn't work

Arun S

unread,
Aug 6, 2017, 11:22:50 PM8/6/17
to Django users
The Models Look like this :

stage_state = models.ForeignKey(EvalState, verbose_name="Eval State")
class Bundle(AtlasAuditModel, AtlasBaseHelper):^M
    """^M
    Represents the bundle purchased by the customer. The bundle^M
    contains a reference identifier which remains the same if the^M
    the bundle is either upgraded or entended.^M
    A bundle can have 0 or more features.^M
    """^M
    bundle_id = models.CharField(verbose_name="Bundle ID",^M
                                 max_length=32,^M
                                 unique=True)^M
....
....
....
    stage_state = models.ForeignKey(EvalState, verbose_name="Eval State")


atlas_bundle;
atlas_bundle | CREATE TABLE `atlas_bundle` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
 ...
....
...
  `stage_state_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `atlas_bundle_36c1765e` (`stage_state_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1408 DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC |
19 rows in set (0.01 sec)

desc evalstate;
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| name          | varchar(32)  | NO   | UNI | NULL    |                |
| friendly_name | varchar(32)  | NO   | UNI | NULL    |                |
| description   | varchar(255) | YES  |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

Whats the Difference in having qs when there is a foriegn Key value?

Arun

lemme smash

unread,
Aug 7, 2017, 6:07:04 AM8/7/17
to Django users
i meant EvalState model
if name attribute on it is a ForeignKey you should get corresponding queryset of model it links to
if it's charfield, you should use text choices 

Arun S

unread,
Aug 7, 2017, 6:39:49 AM8/7/17
to Django users
Can you just give an Example for this taking a Query.

lemme smash

unread,
Aug 7, 2017, 6:43:33 AM8/7/17
to Django users
you didn't show me a model structure, you just showed another model, so I can't give you example without picture of what's going on there

Arun S

unread,
Aug 7, 2017, 6:58:00 AM8/7/17
to Django users
class EvalState(models.Model,AtlasBaseHelper):
    """
    Represents Eval State:
    ACTIVE
    INACTIVE
    DELETE
    NA
    """
    name = models.CharField(max_length=32, unique=True)
    friendly_name = models.CharField(max_length=32, unique=True)
    description = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        verbose_name = "Eval States"

    def __unicode__(self):
        return self.name


class Bundle(AtlasAuditModel, AtlasBaseHelper):^M
    """^M
    Represents the bundle purchased by the customer. The bundle^M
    contains a reference identifier which remains the same if the^M
    the bundle is either upgraded or entended.^M
    A bundle can have 0 or more features.^M
    """^M
    bundle_id = models.CharField(verbose_name="Bundle ID",^M
                                 max_length=32,^M
                                 unique=True)^M
    customer = models.ForeignKey(Customer)^M
    description = models.CharField(max_length=255, blank=True, null=True)^M
    state = models.ForeignKey(BundleState)^M
    extended_state = models.ForeignKey(BundleExtendedState)^M
    type = models.ForeignKey(BundleType)^M
    quantity = models.FloatField(blank=False)^M
    start_date = models.DateField(verbose_name="Start Date")^M
    end_date = models.DateField(verbose_name="End Date")^M
    stage = models.CharField(max_length=32, blank=True, null=True)^M
    stage_state = models.ForeignKey(EvalState, verbose_name="Eval State", null=True)

The Below is the Migration Script written to add the States in to EvalState:
def forwards(apps, schema_editor):
    DcPropertyType = apps.get_model("atlas", "evalstate")
    db_alias = schema_editor.connection.alias

    DcPropertyType.objects.using(db_alias).bulk_create([
        DcPropertyType(name="ACTIVE", friendly_name="EVAL Active", description="Bundle EVAL State is ACTIVE"),
        DcPropertyType(name="INACTIVE", friendly_name="EVAL InActive",description="Bundle EVAL state is INACTIVE"),
        DcPropertyType(name="DELETE", friendly_name="EVAL Delete", description="Bundle EVAL state is DELETE"),
        DcPropertyType(name="NA", friendly_name="EVAL NotApplicable", description="Bundle EVAL state is not applicable")
    ])

def backwards(apps, schema_editor):
    DcPropertyType = apps.get_model("atlas", "evalstate")
    db_alias = schema_editor.connection.alias

    DcPropertyType.objects.using(db_alias).filter(name="ACTIVE", description="Bundle EVAL State is ACTIVE").delete()
    DcPropertyType.objects.using(db_alias).filter(name="INACTIVE", description="Bundle EVAL state is INACTIVE").delete()
    DcPropertyType.objects.using(db_alias).filter(name="DELETE", description="Bundle EVAL state is DELETE").delete()
    DcPropertyType.objects.using(db_alias).filter(name="NA", description="Bundle EVAL state is not applicable").delete()


class Migration(migrations.Migration):

    dependencies = [
        ('atlas', '0012_add_eval_states'),
    ]

    operations = [
        migrations.RunPython(forwards, backwards),
    ]

Does this make sense for the model structure. I do not have any Models Diagram for the same.

---
Arun
Reply all
Reply to author
Forward
0 new messages