showing the checked item alone without check box

孤街浪徒 提交于 2019-11-28 10:51:32

问题


forms.py

PERSON_ACTIONS = (
    ('1', '01.Allowed to rest and returned to class'),
    ('2', '02.Contacted parents /guardians'),
    ('3', '02a.- Unable to Contact'),
    ('4', '02b.Unavailable - left message'),)

class PersonActionsForm(forms.ModelForm):
   action = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=PERSON_ACTIONS, required=False, label= u"Actions")

models.py

class Actions(models.Model):
    report = models.ForeignKey(Report)
    action =  models.IntegerField('Action type')

print.html

{{ actionform.as_p}}

The PersonActionsForm contains the items with multichoice checkbox. In report registration page,the user can select any one or more item.The checked items are saved in models as integer values.

Since i am rendering the whole form it is showing the entire form with checked and unchecked item.

In print page,i want to show only the checked item alone without checkbox.

How to do this in django.

Thanks


回答1:


Based on James's answer. You can move PERSON_ACTIONS to your model and import it in form.

models.py:

PERSON_ACTIONS = (
    ('1', '01.Allowed to rest and returned to class'),
    ('2', '02.Contacted parents /guardians'),
    ('3', '02a.- Unable to Contact'),
    ('4', '02b.Unavailable - left message'),
)
PERSON_ACTIONS_DICT = dict(PERSON_ACTIONS)

class Actions(models.Model):
    report = models.ForeignKey(Report)
    action =  models.IntegerField('Action type')

    def action_as_text(self):
        return PERSON_ACTIONS_DICT.get(str(self.action), None)

forms.py:

from .models import PERSON_ACTIONS

class PersonActionsForm(forms.ModelForm):
    action = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple(), 
        choices=PERSON_ACTIONS, 
        required=False, 
        label= u"Actions"
    )

Get the actions in views.py:

actions = Actions.objects.filter(....)
return render(request, 'your_template.html', {
    .....
    'actions': actions   
})

... and render it in template:

{% for action in actions %}
    {{ action.action_as_text }}
{% endfor %}

Hope this helps.




回答2:


You shouldn't be using forms for non-edit display purposes. Instead, make a method on your class:

from forms import PERSON_ACTIONS
PERSON_ACTIONS_DICT = dict(PERSON_ACTIONS)

class Actions(models.Model):
    report = models.ForeignKey(Report)
    action =  models.IntegerField('Action type')

    def action_as_text(self):
        return PERSON_ACTIONS_DICT.get(str(self.action), None)

Then you can just do {{ obj.action_as_text }} in a template and get the text you want. Note that it would probably be more common to use integers in the PERSON_ACTIONS array (then you don't need the str call in action_as_text.)



来源:https://stackoverflow.com/questions/17652075/showing-the-checked-item-alone-without-check-box

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