Form Django Loads Values but Not Saved

Asked

Viewed 103 times

0

I did a lot of research on my case on the Internet and I couldn’t find an answer that fits my problem.

Following the tip of JACKSON MOURA in this answer you gave me in another case this one: Doubt About the logged-in usurer

I was able to assemble the form taking the data of the flock and starting filled as necessary that it is follows the code:

py.models

class CadastroDoPaciente(models.Model):

    nome = models.CharField(max_length=50)
    sexo = models.ForeignKey(SexoDoPaciente, on_delete=models.CASCADE)
    nome_da_mae = models.CharField(max_length=50)
    cartao_sus = models.BigIntegerField()
    data_nascimento = models.DateField()
    cpf = models.IntegerField()
    municipio = models.ForeignKey(Municipos, on_delete=models.CASCADE)
    be = models.IntegerField()

    def __str__(self):
        return self.nome

class RegulacaoPaciente(models.Model):

    r_nome = models.ForeignKey(CadastroDoPaciente, on_delete=models.CASCADE, related_name='r_nome', default='nome')
    r_sexo = models.ForeignKey(CadastroDoPaciente, on_delete=models.CASCADE, related_name='r_sexo', default='sexo')
    r_cartao_sus = models.ForeignKey(CadastroDoPaciente, on_delete=models.CASCADE, related_name='r_cartao_sus', default='cartao_sus')
    r_data_nascimento = models.ForeignKey(CadastroDoPaciente, on_delete=models.CASCADE, related_name='r_data_nascimento', default='data_nascimento')
    r_cpf = models.ForeignKey(CadastroDoPaciente, on_delete=models.CASCADE, related_name='r_cpf', default='cpf')
    r_municipio = models.ForeignKey(CadastroDoPaciente, on_delete=models.CASCADE, related_name='r_municipio', default='municipio')
    r_be = models.ForeignKey(CadastroDoPaciente, on_delete=models.CASCADE, related_name='r_be', default='be')
    cadastrarcartaosisreg = models.CharField(max_length=50)
    hospital_de_origem = models.CharField(max_length=20)
    hospital_de_destino = models.ForeignKey(Hospitais, on_delete=models.CASCADE)
    vincularlocomocaopaciente = models.ForeignKey(LocoMocaoPaciente, on_delete=models.CASCADE)
    reservadeleito = models.CharField(max_length=50)# criar status para em trasito / ocupado
    hospitalarinformarnumeroaih = models.CharField(max_length=50)
    tipoveiculousado = models.CharField(max_length=50)
    observacoesgerais = models.TextField()

    def __str__(self):
        return self.nome

Forms.py

class Regulacao_Do_Paciente_Form(ModelForm):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(Regulacao_Do_Paciente_Form, self).__init__(*args, **kwargs)
        self.fields['r_nome'].initial = str(self.instance.nome)
        self.fields['r_sexo'].initial = str(self.instance.sexo)
        self.fields['r_cartao_sus'].initial = str(self.instance.cartao_sus)
        self.fields['r_data_nascimento'].initial = str(self.instance.data_nascimento)
        self.fields['r_cpf'].initial = str(self.instance.cpf)
        self.fields['r_municipio'].initial = str(self.instance.municipio)
        self.fields['r_be'].initial = str(self.instance.be)
        self.fields['hospital_de_origem'].initial = globals.user.employee.unidade

    class Meta:
        model = RegulacaoPaciente

        fields = [
            'r_nome',
            'r_sexo',
            'r_cartao_sus',
            'r_data_nascimento',
            'r_cpf',
            'r_municipio',
            'r_be',
            'cadastrarcartaosisreg',
            'vincularlocomocaopaciente',
            'reservadeleito',
            'hospitalarinformarnumeroaih',
            'tipoveiculousado',
            'observacoesgerais',
            'hospital_de_origem',
            'hospital_de_destino',
        ]
        widgets = {
            'r_nome': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'r_sexo': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'r_cartao_sus': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'r_data_nascimento': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'r_cpf': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'r_municipio': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'r_be': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'cadastrarcartaosisreg': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'vincularlocomocaopaciente': Select(attrs={'class': 'form-control', 'readonly': False}),
            'reservadeleito': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'hospitalarinformarnumeroaih': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'tipoveiculousado': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'observacoesgerais': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'hospital_de_origem': TextInput(attrs={'class': 'form-control', 'readonly': False}),
            'hospital_de_destino': Select(attrs={'class': 'form-control', 'readonly': False}),
        }

py views.

class Regulacao_do_Pacinete_CreateViews(LoginRequiredMixin, PermissionRequiredMixin, CreateView, UpdateView):
    form_class = Regulacao_Do_Paciente_Form
    model = CadastroDoPaciente    
    template_name = "principal/regulacao_do_paciente.html"
    success_url = reverse_lazy('index')

Result of the Code:Resultado esperado

when I click to save of this error that I tried in several ways within the reach of my knowledge to solve and I could not.

follows the error: Erro ao salvar

  • 1

    You have set your form fields to "readonly".. Where the data comes from to fill these fields?

  • It comes from the model Registration dope, I had not thought that the "readonly" could influence the auto fill

  • 1

    I believe that the readonly does not really influence.. I just wanted to better understand your question.. What exactly do you want this form to do? You already have the data from "Registration" and just want to include the new data from "Regulacaopaciente"?

  • Exactly, the "Regulacaopaciente" models will be created based on the "Cadastral", then the fields referring to the registration are started with the data of the registration and I add to the other fields the added data, to generate the content of the "Regulacaopaciente"..

1 answer

1

Because Voce doesn’t make your model Cadastral like this:?

class RegulacaoPaciente(models.Model):

    cadastro_do_paciente = models.ForeignKey(CadastroDoPaciente, on_delete=models.CASCADE)
    cadastrarcartaosisreg = models.CharField(max_length=50)
    hospital_de_origem = models.CharField(max_length=20)
    hospital_de_destino = models.ForeignKey(Hospitais, on_delete=models.CASCADE)
    vincularlocomocaopaciente = models.ForeignKey(LocoMocaoPaciente, on_delete=models.CASCADE)
    reservadeleito = models.CharField(max_length=50)# criar status para em trasito / ocupado
    hospitalarinformarnumeroaih = models.CharField(max_length=50)
    tipoveiculousado = models.CharField(max_length=50)
    observacoesgerais = models.TextField()

    def __str__(self):
        return self.nome

Instead of placing each field of the "Registration" model, install the entire object...

About your question... What new data do you want to save? What data do you already have? From this existing data, do you want to change some? The answer depends on these observations


Continuing the response according to your comment..

If what Voce wants to save is the "Regulacaopaciente" model data, then your View has to say this:

class Regulacao_do_Pacinete_CreateViews(LoginRequiredMixin, PermissionRequiredMixin, CreateView, UpdateView):
    form_class = Regulacao_Do_Paciente_Form
    model = RegulacaoPaciente  # Este model é que terá os dados salvos
    template_name = "principal/regulacao_do_paciente.html"
    success_url = reverse_lazy('index')

You will create a new model object "Regulacaopaciente", instantiate the object (that Voce already has) of the model "Registration" and put this object in the new field patient registration

  • I think that’s what I’m flying, I really don’t need to create the same fields of the Register right? I just need to create a field for references the registration and add the new fields is this?

  • 1

    I believe that’s right.

  • I will refactoring and speak the result, thank you very much for your help.

  • Hello Vinicius Bussola! You were right after I remade the model it is saving everything perfect, mai sai arose a doubt of mine, how to display the existing fields within the foreing Key without that influencing the form? I tried to rescue using a query more error because I don’t know how to do. I am searching here how to do. Thanks so much for the help.

  • 1

    Voce can do something like: regulation = Regulacaopaciente.objects.get(id=1) name = regulation.cadastro_do_patient.nomen.... If you still have doubts, open another question

Browser other questions tagged

You are not signed in. Login or sign up in order to post.