如何使用ModelMultipleChoiceField获取模板中用户的全名

时间:2018-07-10 15:27:43

标签: django django-forms django-templates

我的表单看起来像这样:

```{r, results = "asis"}
fruits <- c("apple", "banana", "grape")
for(i in fruits) {
    cat(paste0("![](", "~/Desktop/R/Files/", i, ".jpg)"), "\n")
}
```

这是我模板的一部分

"![](~/Desktop/R/Files/apple.jpg)"

我想获取每个用户的全名而不是用户名,我该怎么做。

编辑

我的模特:

class ProjectForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(ProjectForm, self).__init__(*args, **kwargs)
    members = forms.ModelMultipleChoiceField(
        label="Members",
        queryset=User.objects.all(),
        widget=forms.CheckboxSelectMultiple,
        required=False,
    )

    class Meta:
        model = Project
        fields = ['title', 'description', 'objective', 'duration', 'members']

2 个答案:

答案 0 :(得分:1)

所以,现在我想我明白了。您要手动呈现表单,以便全名显示为复选框的标签。为此,您必须访问成员的queryset属性。

这是它的样子,

 <form action="" method="post">
     {% for name, field in project_form.fields.items %}
         {% ifequal name 'members' %}

            <div>
                 <label>{{ field.label }}: </label>
                 <ul>
                 {% for member in field.queryset %}
                     <li>
                         <label for="id_members_{{ forloop.counter0 }}">
                             <input type="checkbox" name="{{ name }}" >
                             {{ member.get_full_name }}
                         </label>
                     </li>
                 {% endfor %}
                 </ul>
            </div>

         {% else %}
             <div>
                <label for="id_{{ name }}">{{field.label}}: </label>
                <input id="id_{{ name }}" type="{{ field.type }}">
             </div>
         {% endifequal %}
     {% endfor %}
 </form>

答案 1 :(得分:-1)

Models.py

class User(AbstractUser):
    bio = models.TextField(max_length=500, blank=True)
    avatar = models.ImageField(upload_to=upload_to, default='avatars/user.png')

    def __unicode__(self):
          return self.first_name + ' ' + self.last_name

检查