1

I am using a django formset containing forms that specify user friendship preferences.

My form fields are:

    siteuser_id = forms.IntegerField(widget=forms.HiddenInput())
    subscribed = forms.BooleanField(required=False)
    ally = forms.BooleanField(required=False)
    enemy = forms.BooleanField(required=False)

The goal is to display all of a person's friends and that person's status within the game.

When I display the forms in the formset, I'd like to display the nickname (nicknames are not unique or I would just use it instead of siteuser_id) of the person alongside the friendship preference for that person.

I tried making username a form field, but that makes it editable, and I just want it to display within the table, not be editable.

Help?

Foo Party
  • 596
  • 1
  • 4
  • 13

4 Answers4

1

Just add the readonly attribute to the field:

username = forms.CharField(widget=forms.TextInput(attrs={"readonly": "readonly"}))

Makes the field non-editable.

Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
1

In case you are using model formsets (or using them is an option) you can access the instance attribute of the form within the template.

For example:

{% for form in formset %}
    {{ form.instance.nickname }}
    {{ form }}
{% endfor %}
ptrck
  • 731
  • 5
  • 13
1

It sounds like you don't necessarily want a form - you could just pass the data in objects to your template.

However, if you do want to do this with a form, you could set a custom widget for the form field, and subclass Widget. See https://docs.djangoproject.com/en/dev/ref/forms/widgets/.

Marcin
  • 48,559
  • 18
  • 128
  • 201
1

Here is the custom widget I made to do this!

Just put this in a widgets.py file in your project:

from django.forms.widgets import Widget

class DisplayOnlyField(Widget):

    def __init__(self,attrs=None):
        self.attrs = attrs or {}
        self.required = False

    def render(self, name, value="", attrs=None):
        try:
            val = value
        except AttributeError:
            val = ""
        return val

Then in your views.py, put:

from projname.widgets import DisplayOnlyField

And on the field, it would be:

user_name = forms.CharField(widget=DisplayOnlyField())
Foo Party
  • 596
  • 1
  • 4
  • 13