Showing checked item yourself without checkbox

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 element contains elements with the multichoice flag. On the report registration page, the user can select any one or more elements. Validated items are saved as integer values ​​in models.

Since I process the whole form, it shows the whole form with a marked and unchecked element.

On the print page, I want to show only the marked item without a checkmark.

How to do it in django.

thanks

+1
source share
2 answers

Based on James answer. You can move PERSON_ACTIONS to your model and import it into the 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 actions in views.py :

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

... and draw it in the template:

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

Hope this helps.

+1
source

You should not use forms to display without editing. Instead, make a method in 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 the 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 .)

+1
source

Source: https://habr.com/ru/post/947944/


All Articles