Display forms choice in template-Django

一世执手 提交于 2020-01-04 14:08:30

问题


On the template, when I call person.health_issue, I am getting '1','2' instead of 'Abdominal pain','Anaphylaxis'. How to display the value ('Abdominal pain','Anaphylaxis') instead of the code(1 or2 etc).

I tried with this also {{ person.get_health_issue_display }} in template,it is not displayed anything.

forms.py

   HEALTH_USSUES = (
        ('1', 'Abdominal pain'), ('2', 'Anaphylaxis'), ('3', 'Asthma'),
        ('4', 'Bruising'), ('5', 'Chest pains'), ('6', 'Coughs or Colds')
    )
    class PersonActionsForm(forms.ModelForm):

        action = forms.MultipleChoiceField(widget=forms.Select(), choices=HEALTH_USSUES, required=False)

models.py

class ReportPerson(models.Model):
    report = models.ForeignKey(Report)
    name = models.CharField('Name', max_length=100)
    first_aid = models.BooleanField('First aid', default=False)
    health_issue = models.IntegerField(default=0)

views.py

def report_template(request):
     """"""
    person = ReportPerson.objects.get(pk=person_id)
    """"""
     return render(request, 'event/print.html',
             {
              'person':person
             })

can any one tell me how to do this.

Thanks


回答1:


As you don't have any choices set in model field health_issue you need to write the get_health_issue_display method by your self i will name it as health_issue_display so that default get_FOO_display method not gets overridden:

HEALTH_USSUES = (
    (1, 'Abdominal pain'), (2, 'Anaphylaxis'), (3, 'Asthma'),
    (4, 'Bruising'), (5, 'Chest pains'), (6, 'Coughs or Colds')
)

class ReportPerson(models.Model):
    report = models.ForeignKey(Report)
    name = models.CharField('Name', max_length=100)
    first_aid = models.BooleanField('First aid', default=False)
    health_issue = models.IntegerField(default=1)

    def health_issue_display(self):
        for c in HEALTH_USSUES:
            if c[0] == self.health_issue:
                return c[1]

Or just add choices in the model field:

health_issue = models.IntegerField(default=1, choices=HEALTH_USSUES)

Now you have get_health_issue_display.

  • Also make the first value in every choice as integer (1, 'Abdominal pain') rather than string '1'. Just to remove the confusion.
  • You have default=0 which does not exists in choices. Change it to default=1


来源:https://stackoverflow.com/questions/17113974/display-forms-choice-in-template-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!