Django: Set initial value of dropdown in form based on value in model

I am working on a ticketing web application using Django as a university. In there, assignees (tutors) need to be able to asign another tutor and change the status of the ticket ("Open", "In progress", ...).

The current tutor and the current status is saved in the Ticket model:

class Ticket(models.Model):
    creator = models.ForeignKey(
        Student, null=True, on_delete=models.SET_NULL
    )
    assignee = models.ForeignKey(
        Tutor, on_delete=models.SET_NULL, blank=True, null=True
    )
    current_status = models.CharField(
        max_length=2,
        choices=KorrekturstatusEnum.choices,
        default=KorrekturstatusEnum.OFFEN,
    )
    description = models.TextField(
        default="Please provide as much detail as possibile."
    )

The life cycle of a ticket is saved in the Messages model:

class Messages(models.Model):
    class ChangeTypeENUM(models.TextChoices):
        OPEN = "01", "Open"
        ASIGNMENT = "02", "Asignment"
        STATUS_CHANGE = "03", "Status change"
        MESSAGE = "04", "Message"

    class SenderENUM(models.TextChoices):
        TUTOR = "01", "Tutor"
        STUDENT = "02", "Student"

    student = models.ForeignKey(
        Student,
        on_delete=models.SET_NULL,
        null=True,
        related_name="student_messages",
    )
    tutor = models.ForeignKey(
        Tutor,
        on_delete=models.SET_NULL,
        related_name="tutor_messages",
        null=True,
        blank=True,
    )
    ticket = models.ForeignKey(
        ticket, on_delete=models.CASCADE, related_name="korrektur_messages"
    )
    text = models.TextField(null=True, blank=True)
    created_at = models.DateTimeField(default=timezone.now)
    sender = models.CharField(
        max_length=2, choices=SenderENUM.choices, default=SenderENUM.STUDENT
    )
    status = models.CharField(
        max_length=2,
        choices=KorrekturstatusEnum.choices,
        default=KorrekturstatusEnum.OFFEN,
    )
    change_type = models.CharField(
        max_length=2,
        choices=ChangeTypeENUM.choices,
        default=ChangeTypeENUM.EROEFFNUNG,
    )

Changes to a ticket, including messages/comments are done by a from, I'm using a model form here. I am trying to overwrite __init__():

class MessagesForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs)
        korrektur_id = kwargs.pop("korrektur_id")
        korrektur = Korrektur.objects.get(pk=int(korrektur_id))
        self.fields["tutor"] = korrektur.bearbeiter
        self.fields["status"] = korrektur.aktuellerStatus
    class Meta:
        model = Messages
        fields = ("tutor", "status", "text")
        widgets = {
            "text": forms.Textarea(attrs={"cols": 50, "rows": 10}),
        }

In this form, I want the current tutor and status to be the default value of the corresponding drop down.

The url contains the id/pk of the ticket, that change belongs to: path("tickets/<int:ticket_id>", views.EditTicketView.as_view())

The class in views.py for the page with the form, looks like this:

class KorrekturBearbeitenView(View):
    form_class = MessagesForm
    initial = {"key": "value"}
    template_name = "backend/edit-ticket.html"


    @method_decorator(login_required)
    def get(self, request, korrektur_id):
        ticket = Ticket.objects.get(pk=ticket_id)
        ticket.current_state = ticket.get_current_state_display()

        messages = Messages.objects.filter(korrektur=korrektur).order_by(
            "created_at"
        )
        for message in messages:
            message.status = message.get_status_display()
            # message.sender = message.get_sender_display()

        form = self.form_class(initial=self.initial, korrektur_id=korrektur_id)

        return render(
            request,
            self.template_name,
            context={
                "form": form,
                "ticket": ticket,
                "tutor": tutor,
                "messages": messages,
            },
        )

As show, I try to pass ticket_id on to the ModelForm, but this doesn't work. How can I access the ticket object in the MessagesForm init() function?

I know that the initial value of the form can be set by the initial parameter. But how do I get this dynamically from linkes model?

Back to Top