Search code examples
pythondjangodjango-formsdjango-widget

DJango Model form that display's user.profile.name info instead user.username


I have a ModelForm in Django that is used to take attendance at an event. It displays the user as plain text instead of a field:

class PlainTextWidget(forms.Widget):
    def render(self, name, value, attrs=None):
        return mark_safe(value) if value is not None else '-'

class AttendanceForm(forms.ModelForm):
    class Meta:
        model = Registration
        fields = (
            "absent",
            "late",
            "excused",
            "user", # User foreign key
        )

        widgets = { 'student': PlainTextWidget,}

However, instead of having the form display a user's username, which is the default, I would like to display the user's profile string: user.profile.__str__

It seems like I could look it up in PlainTextWidget.render() using value as a filter on a Profiles queryset, but is there a more direct way to access user.profile in the form or the widget?

How can I do this?


Solution

  • You can override init method and save student profile str as member variable of the form:

    class AttendanceForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(AttendanceForm, self).__init__(*args, **kwargs)
            self.student_string = self.instance.student.profile.__str__()
    

    and then use it somewhere in the form:

    <p>{{ form.student_string }}</p>