'python django get_object_or_404 inside form_valid doesn't work

I hope you can help me, I am learning django, particularly class-based views, I have the following code.

I think the get_object_or_404 inside form_valid is not working as it should.

class AgregarEntrada(CreateView):
    model = Entrada
    template_name = 'EntradaCrear.html'
    form_class = FormularioEntrada
    success_url = reverse_lazy('UltimasEntradas')   

    def get_context_data(self, **kwargs):
        obj = get_object_or_404(Empresa, pk = self.kwargs["pk"], slug = self.kwargs["slug"], 
        FechaCreacion = self.kwargs["FechaCreacion"]) 
        contexto = super().get_context_data(**kwargs)
        return contexto

    def form_valid(self, form):
        obj = get_object_or_404(Empresa, pk = self.kwargs["pk"], slug = self.kwargs["slug"], 
        FechaCreacion = self.kwargs["FechaCreacion"]) 
        
        form.instance.empresa_id = self.kwargs["pk"]
        form.instance.UsuarioCreo = self.request.user.username
        
        self.object = form.save()
        form.instance.Entrada = form.instance.pk  
        return super().form_valid(form)

everything works perfect, this view saves the data correctly, even if I go to /pk/slug everything works fine, likewise if I change the slug or the pk in the url it immediately sends me a 404 error, which is so well, the problem lies when someone changes the url once the form has been rendered, for example the pk or the slug, instead of sending me an error, it saves the data as if the pk or the slug were correct.

I want to explain myself better. If I go to url/pk/slug everything works fine, but when someone goes to url/pk/slug and changes it to url/fake-pk/fake-slug the data is still saved as if the url was correct.

What am I doing wrong? I hope you can understand my problem. Guys I Will appreciate any help.

Thank you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source