Saturday, August 5, 2017

Re: Drop Down Menu in Django Forms not working.

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)

On Friday, August 4, 2017 at 8:07:24 PM UTC+3, Arun S wrote:
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.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/569250aa-3644-47b6-a952-e857247e966b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment