我正在使用自定义MultipleChoiceField
,以便显示用户的全名而不是其登录名。
我使用MultipleChoiceField的choices
属性来自定义项目的显示方式:
assignees = MultipleChoiceField(choices=[(user.id, user.get_full_name() or user.username) for user in User.objects.all()])
用户名正确显示,但是问题是是在版本上(即为表单提供了具有现有已分配用户的Story
实例),相应的{{1} }未选中...
我尝试使用<option>
关键字,但没有帮助。
initial
models.py
self.fields['assignees'] = MultipleChoiceField(choices=[(user.id, user.get_full_name() or user.username) for user in User.objects.all()],
initial=[user.id for user in self.instance.assignees])
forms.py
class Story(BaseModel):
assignees = models.ManyToManyField(User,
blank=True,
related_name="assigned")
views.py
class StoryForm(forms.ModelForm):
assignees = MultipleChoiceField(choices=[(user.id, user.get_full_name() or user.username) for user in User.objects.all()])
story_form.html
def story_edit(request, story_id):
if request.method == 'POST':
story = get_object_or_404(Story, id=story_id)
form = StoryForm(request.POST, instance=story)
if form.is_valid():
form.save()
else:
story = get_object_or_404(Story, id=story_id)
form = StoryForm(instance=story)
return render(request, 'story_form.html', {'form': form})