0

I'm making a ModelForm. I have a Gender field in which I have given choices.In forms.py file I have converted those choices into checkbox using widget.

models .py

class UserModel(models.Model):
    #username=models.ForeignKey(
    #    on_delete=models.CASCADE,
     #   related_name='custom_user')

    name=models.CharField(
        max_length=50,
        verbose_name='Full Name',
    )

    gender=models.CharField(
        choices=(
            ('M','Male'),
            ('F','Female'),
        ),
        max_length=1,
        verbose_name='Gender',
        default='M'
    )

forms.py

class UserForm(forms.ModelForm):


    class Meta:
        model=UserModel
        exclude=()
        widgets = {
            'DOB': forms.SelectDateWidget(),
            'gender':forms.RadioSelect(),
            #'hobbies':forms.CheckboxSelectMultiple()

        }

everything works fine and data is stored in database,But when I fetch data from the database in django shell using commands.Instead of getting the name of choice I get 'M',or 'F'. I know for choice field we can use object_of_modelclass.get_gender_display to get name of choice and it returns full name of choice. But since I have converted the choice to checkbox field in forms.py,now when I fetch data from database using object_of_modelclass.get_gender_display it returns

Django shell commands im using:

from .models import UserModel
a=Usermodel.objects.get(pk=1)
a.get_gender_display

it returns

functools.partial(<bound method Model._get_FIELD_display of <UserModel: hoo>>, field=<django.db.models.fields.CharField: gender>)

How can I get original name as "Male' and 'Female' ? Thanks

3
  • You haven't shown the relevant code here. Where are you calling get_gender_display? Commented Jul 16, 2019 at 8:30
  • in django shell by using comands,wait I'll update question @DanielRoseman Commented Jul 16, 2019 at 8:31
  • 1
    how about a.get_gender_display() Commented Jul 16, 2019 at 8:45

1 Answer 1

2

You should call the get_FIELD_display as a function, therefore using ().

a.get_gender_display()
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks It worked.Can you explain why we have to call it as function?
Basically, all fields that has a choices has this method available which returns the value of the choice. You can check more here
how can I perform same functionality for admin site?
Have a look here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.