Formset configuration

Hi,

I’m trying to use a Formset_factory form so the user can update multiple records on the same template. But I need that only one field is enabled for update.

I’m getting the data from a classe model only with FK.

What happens is if I use a widget on the field to set it as read-only, the form only displays the IDs but if I don’t run that line on the form I get the name of the student and I can update it.

How can I make the field showning the name and at the same time being read-only?

Here is my code so far:

model class

class Registers(models.Model):

    class Meta:
        verbose_name_plural = 'Registers'

    lesson_at = models.DateTimeField(auto_now_add=True)
    regclasseid = models.ForeignKey(Turmas, on_delete=models.CASCADE, verbose_name="Classe:")
    regalunoid = models.ForeignKey(Alunos, on_delete=models.CASCADE, verbose_name="Aluno:")

    PRESENT_ABSENT = (
        ('P', 'Present'),
        ('A', 'Absent'),
    )

    status = models.CharField(max_length=1, choices=PRESENT_ABSENT, verbose_name="Presence/Absence:")

    def __int__(self):
        return self.regalunoid

form

from django import forms
from .models import Registers


class RegisterForm(forms.ModelForm):
    regalunoid = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly'}))

    class Meta:
        model = Registers
        fields = ["regalunoid", "status"]

view

def RegisterUpdate(request, **kwargs):

    t = Turmas.objects.get(id=kwargs['pk'])

    RegisterFormSet = modelformset_factory(Registers, form=RegisterForm)
    form = RegisterFormSet(queryset=Registers.objects.filter(regclasseid=kwargs['pk']))
    return render(request, 'schooladmin/registers.html', {'form': form, 'turma': t})


Screenshot 2023-11-26 at 16.07.05

Thanks in advance

The issue here is that the Model field regalunoid is a ForeignKey, but you’re trying to render it as a TextInput field.

By default, the ForeignKey field should render as a ModelChoiceField, with the display value being defined by the __str__ method on the target model (Alunos).

I think you can get the result you want by using the ModelChoiceField as the field type, using the select widget with the disabled attribute True.

Note: Do not rely upon the readonly attribute (it’s not relevant to select fields anyway). You want to use the disabled attribute.

Thank you, it’s working now!

Two last questions about these forms:

1 - Can we use CSS on them?
2 - How can we get rid off the last empty row?

Yes, the same way you would style any form.

See the information about the extra attribute in the docs.

Thanks you for your help.