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?

4

4 回答 4

1

这是我为此制作的自定义小部件!

只需将其放在项目中的 widgets.py 文件中:

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

然后在你的views.py中,输入:

from projname.widgets import DisplayOnlyField

在球场上,它将是:

user_name = forms.CharField(widget=DisplayOnlyField())
于 2013-10-08T16:14:41.787 回答
1

只需将readonly属性添加到该字段:

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

使字段不可编辑。

于 2013-10-07T22:12:27.907 回答
1

如果您使用模型表单集(或使用它们是一个选项),您可以访问instance模板中表单的属性。

例如:

{% for form in formset %}
    {{ form.instance.nickname }}
    {{ form }}
{% endfor %}
于 2013-10-07T22:24:39.603 回答
1

听起来您不一定想要一个表单 - 您可以将对象中的数据传递给您的模板。

但是,如果您确实想对表单执行此操作,则可widget以为表单字段和 subclass设置自定义Widget。请参阅https://docs.djangoproject.com/en/dev/ref/forms/widgets/

于 2013-10-08T14:41:20.457 回答