I have the following Models and Forms:
#models.py
class NetworkDevice(models.Model):
user = models.ForeignKey(User)
device_name = models.CharField(_('device name'), max_length=100)
...
#forms.py
class NetworkDevicesForm(ModelForm):
class Meta:
model = NetworkDevice
fields=('user', 'device_name',...)
'...' are some fields I left out, since they are not important for this. I want to create a formset based on my ModelForm:
#views.py
in some view:
network_device_formset = modelformset_factory(models.NetworkDevice,
extra=0, form=NetworkDevicesForm, fields=(
'user', 'device_name', ...))
And I display it like this in my template:
<form action="{% url 'some:action' %}" method="post">
{% csrf_token %}
{{ devices_formset.management_form }}
<table>
{% for form in devices_formset %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
{% endfor %}
<tbody>
{% for form in devices_formset %}
<tr>
{% for field in form %}
<td>{{ field }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
<input type="submit" value='{% trans "Save" %}'/>
</form>
Now this will display my ForeignKey with an HTML select tag. I don't even want to show all the choices there however. I just want to display the key for the according instance. I can disable the select tag:
class NetworkDevicesForm(ModelForm):
class Meta:
model = NetworkDevice
fields=('user', 'device_name', ...more fields)
widgets = {'user': widgets.Select(attrs={'readonly': True,
'disabled': True})}
But then I get errors on the validation of the user field. Guess I could overwrite the validation for this somehow. But still this would display all the options for the foreign key in the generated html. Is there no way I can just display the value in my template without specifying it in the ModelForm, since I don't want to edit it. Some magic like:
<tbody>
{% for form in devices_formset %}
<tr>
<td>{{ form.user }}</td>
{% for field in form %}
<td>{{ field }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
Except that {{ form.user }} is not working. Can I access that somehow in the template? Hope I was clear about what I want to do and it's possible.