Django DateField persistence

I have a model / Form / view for a request that works well, but when I want to update a request all the fields are loaded except the due_date field (with a date widget) witch remains empty. If I don’t pay attention I validate and the due_date become None. I would like it to load the date that was saved during creation by default and then I modify it or not. Here is the code.

Model

class Request(models.Model):
    thematic = models.ForeignKey(
        Thematic,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name="Thématique",
    )
    context = models.ForeignKey(
        Context,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name="Contexte",
    )
    technical_element = models.CharField(
        max_length=255, verbose_name="Élément technique", blank=True, null=True
    )
    due_date = models.DateField(verbose_name="Date d'échéance", blank=True, null=True)

    def __str__(self):
            return self.context

    class Meta:
        verbose_name = "Request"
        verbose_name_plural = "Requests"

Forms

class RequestForm(forms.ModelForm):
    new_thematic = forms.CharField(
        max_length=255, required=False, label="New Thematic"
    )
    new_context = forms.CharField(
        max_length=255, required=False, label="New Context"
    )
    due_date = forms.DateField(
        widget=forms.DateInput(attrs={"type": "date"}),
        required=False,
    )

    class Meta:
        model = Demande
        fields = "__all__"
        widgets = {
            "thematic": forms.Select(attrs={"class": "form-control"}),
            "context": forms.Select(attrs={"class": "form-control"}),
            "technical_element": forms.TextInput(attrs={"class": "form-control"}),
            "due_date": forms.DateInput(
                attrs={"class": "form-control", "type": "date"}
            ),
        }

    def __init__(self, *args, **kwargs):
        super(DemandeForm, self).__init__(*args, **kwargs)
        if "instance" in kwargs:
            instance = kwargs["instance"]
            if instance.due_date:
                self.fields["due_date"].initial = instance.due_date
        self.fields["thematic"].queryset = Thematic.objects.all()
        self.fields["context"].queryset = Context.objects.all()

    def save(self, commit=True):
        instance = super(DemandeForm, self).save(commit=False)
        new_thematic_name = self.cleaned_data.get("new_thematic")
        new_context_description = self.cleaned_data.get("new_context")

        if new_thematic_name:
            thematic, created = Thematic.objects.get_or_create(name=new_thematic_name)
            instance.thematic = thematic

        if new_context_description:
            context, created = Context.objects.get_or_create(
                description=new_context_description
            )
            instance.context = context

        if commit:
            instance.save()
        return instance

Views

class UpdateRequestView(View):
    def get(self, request, pk):
        request_instance = get_object_or_404(Request, pk=pk)
        request_form = RequestForm(instance=request_instance)
        return render(
            request,
            "operation/update_request_form.html",
            {
                "request_form": demande_form,
                "request_instance": request_instance,
                "title": f"Modify the request {request_instance.context}",
            },
        )

    def post(self, request, pk):
        request_instance = get_object_or_404(Request, pk=pk)
        request_form = RequestForm(request.POST, instance=request_instance)
        if request_form.is_valid():
            instance = request_form.save(commit=False)
            due_date = request_form.cleaned_data.get("due_date")
            if due_date:
                instance.due_date = due_date
            instance.save()
            messages.success(request, "The request was successfully updated.")
            return redirect(reverse("drequest_detail", args=[instance.id]))
        else:
            for field, errors in request_form.errors.items():
                for error in errors:
                    messages.error(request, f"Error {field}: {error}")
        return render(
            request,
            "operation/update_request_form.html",
            {
                "request_form": demande_form,
                "request_instance": request_instance,
                "title": f"Modify the request {request_instance.context}",
            },
        )

In the POST part I have already tried something to display the value of due_date but it does not work.

I tried the init in the form part and another solution in the post part of the view.

New contributor

Tyrael is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật