djangoformsforeign-keyshidden-field

Django - Form - ForeignKey - Hidden - Default value


I have a Hidden ForeignKey in an update form that I want to set to value of default value of 2 in my html form, but I can't get it to work.

forms.py

    eval_sent_state = forms.ModelChoiceField(widget=forms.HiddenInput(), initial=2,queryset=models.EvalUrlSentState.objects.all())

The Html output i get:

<input type="hidden" name="eval_sent_state" value="1" id="id_eval_sent_state">

from views.py

class ClassSchoolTeacherUpdateView(generic.UpdateView):
    model = models.ClassSchool
    form_class = forms.ClassSchoolTeacherForm
    pk_url_kwarg = "pk"

    def get_object(self, queryset=None):
        return models.ClassSchool.objects.get(class_random_key=self.kwargs.get("random"))

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['username'] = self.kwargs.get('username')
        context['random'] = self.kwargs.get('random')
        return context

from models.py:

class ClassSchool(models.Model):

    # Relationships
    eval_sent_state = models.ForeignKey("EvalUrlSentState", default=1,  on_delete=models.SET_NULL, blank=True, null=True)

    # Fields
    class_name = models.CharField(max_length=100)
    class_student_size = models.IntegerField(blank=True, null=True)
    class_subject = models.CharField(max_length=100)
    class_element_name = models.CharField(max_length=100)
    class_teacher_user = models.CharField(max_length=100)
    class_teacher_name = models.CharField(max_length=100, blank=True, null=True)
    eval_year = models.IntegerField(default=2022)
    class_random_key = models.CharField(max_length=8)
    eval_url = models.CharField(max_length=400)
    eval_open_datetime = models.DateTimeField(null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True, editable=False)
    last_updated = models.DateTimeField(auto_now=True, editable=False)

Solution

  • You can override your form to always set the eval_sent_state field to the value you want in the save method, you should remove the field from the form fields though

    class ClassSchoolTeacherForm(forms.ModelForm):
    
        class Meta:
            model = ClassSchool
            exclude = ['eval_sent_state']
    
        def save(self, *args, **kwargs):
            self.instance.eval_sent_state_id = 2
            return super().save(*args, **kwargs)