0

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?

43Tesseracts
  • 4,617
  • 8
  • 48
  • 94

1 Answers1

1

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>
Alexander Tyapkov
  • 4,837
  • 5
  • 39
  • 65
  • 1
    when you create the form then you probably provide the instance of Registration to the form. If this instance exists then you can access it with self.instance.student.profile – Alexander Tyapkov Dec 12 '16 at 08:41