how do I handle a dropdown in Django whose only purpose is to get data.

60 views
Skip to first unread message

eil...@themaii.org

unread,
Jan 24, 2018, 5:19:32 PM1/24/18
to Django users
I need to create an edit box called handicapped with three drop down options on the display:
  0 - none
  1 - Mental
  2 - Phyiscal

and connect it to the handicapped field init(11) in the family database

I know I have to do something like:

            if form['handicapped'].data == 1 or 2:
                q = context['child_filter'].filter(Q(handicapped=handicapped_dict[request.POST['handicapped']]))

>>> But I'm really confused about the above part.

# start of output using search parameters

            if q.count() > 1:
              search_message = "There are %s children that match your selection of %s"  %  (q.count(), request.POST['gender'])
            else:
              search_message = "There is 1 child that matches your selection of %s"  %  (request.POST['gender'])

            if q.count() > 1:
               search_message = ", age: %s"  %  (request.POST['age'])
            else:
               search_message = ", age: %s"  % (request.POST['age'])

            if form.data['handicapped'] is 'Physical' or 'Mental':
               if q.count() > 1:
                  search_message = ", is %s handicapped" %  (request.POST['handicapped'])
               elif q.count() == 1:
                  search_message = ", is %s handicapped" % (request.POST['handicapped'])
            else:
                search_message = ", are %s handicapped" % (request.POST['handicapped'])

but it doesn't _work at all_.

I should say the database is defined correctly.

I get lots of different types of errors - sorry I can't include them now, ...

I am  trying to find the children (already in the database) who may or may not have one of two types of handicaps.


I _do_ use Form. The form file contents follow:
from django import forms
from .widgets import ChainedSelectWidget
from .models import Child


class SponsorForm(forms.Form):
    child = forms.IntegerField()


class FilterForm(forms.Form):
    gender = forms.ChoiceField(choices=[(x, x) for x in ('-----', 'MALE', 'FEMALE')], required=False)
    age = forms.ChoiceField(choices=[(x, x) for x in range(1, 18)], required=False)
#    orphaned = forms.BooleanField(initial=False,required=False)
#    extreme_need = forms.BooleanField(initial=False,required=False)
    handicapped = forms.ChoiceField(choices=[(x, x) for x in ('-------', 'Mental', 'Physcal')], required=False)

    def __init__(self, *args, **kwargs):
        super(FilterForm, self).__init__(*args, **kwargs)

        if 0 == len(self.data):
            self.fields['age'].queryset = Child.objects.none()

        # assign a widget to second select field
        self.fields['age'].widget = ChainedSelectWidget(
            parent_name='gender',         # the name of parent field
            app_name='sponsorship',            # the name of model's application
            model_name='child',          # the name of a model with the method
            method_name='get_children',  # the name of queryset method
            )


-Eileen

Melvyn Sopacua

unread,
Jan 26, 2018, 8:12:19 PM1/26/18
to django...@googlegroups.com
There are a bunch of issues with this code:

1) Spell Physical correctly:


> 2 - Phyiscal

> if form.data['handicapped'] is 'Physical' or 'Mental':

> handicapped = forms.ChoiceField(choices=[(x, x) for x in ('-------',
> 'Mental', 'Physcal')], required=False)

Comparison of non boolean or None values using "is" instead of "==":
> if form.data['handicapped'] is 'Physical' or 'Mental':

Use of or as if natural language in RHS of comparisons (should be a == x or a
== y, not a == x or y):

> if form.data['handicapped'] is 'Physical' or 'Mental':
> if form['handicapped'].data == 1 or 2:

So this reads as if someone with very little knowledge of Python is modifying
a 3rd party app, written by someone with a decent amount of Django experience.

Finally, when accessing form data from a valid form, we access
form.cleaned_data and generally use a local variable to reference the dict:

if form.is_valid():
data = form.cleaned_data
# do stuff with data
--
Melvyn Sopacua

eil...@themaii.org

unread,
Jan 26, 2018, 9:25:55 PM1/26/18
to Django users

well, you certainly got me correct! I'm fairly new to python - didn't do much coding to learn. Trial by fire, sort of. and the original person who put this together is now gone from the company and won't answer any outstanding questions. Plus, I think he got most of the code from 3rd party sources. I could be wrong on that. I was raised on Perl and PL/I (as ancient as the latter may seem)

Melvyn Sopacua

unread,
Jan 30, 2018, 7:54:21 PM1/30/18
to django...@googlegroups.com

On vrijdag 26 januari 2018 22:25:55 CET eil...@themaii.org wrote:

> well, you certainly got me correct! I'm fairly new to python - didn't do

> much coding to learn. Trial by fire, sort of. and the original person who

> put this together is now gone from the company and won't answer any

> outstanding questions. Plus, I *think* he got most of the code from 3rd

> party sources. I could be wrong on that. I was raised on Perl and PL/I (as

> ancient as the latter may seem)

 

I meant to follow this up, didn't have the opportunity till now.

 

I strongly suggest to get the python basics down. Your Perl hash is your python dict, array is a list (tuple for "read only" lists) and you have you basic scalars with str, bool, int and float. And you have objects. In fact, everything, including scalars, class definitions, methods and functions are objects.

 

Standard comparison is "==". The "is" comparison is stricter and only used for boolean values and the special value None (also handy to know is that functions / methods that do not return anything actually return None).

 

One can think of "is" comparison as "equal to and of the same type":

 

>>> empty = ''

>>> empty is None

False

>>> empty is False

False

>>> empty is True

False

>>> bool(empty)

False

>>> bool(empty) is False

True

>>> bool(None)

False

 

If you want a quick intro to Python, I highly suggest Python Tips.


Finally, it's important to know Django
project layout and in your case, getting a handle on views and querysets.

Reply all
Reply to author
Forward
0 new messages