Populate field from 2 other fields

I save in the models I have 3 character fields
Last Name, First Name, Master Data.
The first 2 I put in the input, the 3 (Master Data) I defined readOnly

    Master Data = models.CharField(max_length=50, blank=False, null=False)
    Last Name = models.CharField(max_length=20, blank=False, null=False)
    First Name = models.CharField(max_length=20, blank=False, null=False)

In the view entry function, I entered the code to read the Last Name and First Name fields to populate the Master field, but it doesn’t work and I don’t understand why

    def post(self, request):
        form = AssociateForm(request.POST)
        if form.is_valid():
            associate = form.save(commit=False)
            # common.Registry = request.Registry
            last name = form.cleaned_data.get('Last Name', '')
            first name = form.cleaned_data.get('First name', '')
            # associate.Master Data = last name + ' ' + first name
            associate.Master Data = 'aaaaaaaa'
            print('yyyyy ', last name)
            # When no photo is inserted, store the link to the Base file.

            if 'Photo' in request.FILES:
                associate.Photo = request.FILES['Photo']
                # If no new image has been provided, keep the default value
                associated.Photo = 'Site/Mamozio.png'
            # Add a success message.
            messages.success(request, f "ANAGRAPHIC '{associated.A            # Add a success message
            messages.success(request, f "ANAGRAPHIC '{associate.Master}' - SAVED ")
            # Reset form fields.
            form = AssociateForm()
            print('bbbbb ')
            # Print all form field errors in the terminal
            for field, errors in form.errors.items():
                messages.error(request, f "Error in field {field}: {', '.join(errors)}")
                print(f "Error in field {field}: {', '.join(errors)}")
                print("Error in form.Check console for details.")
                # return HttpResponseBadRequest("Error in form. Check console for details.")

        # Redirect to the same page
        return redirect(reverse('AssociatesInse'))

What we’ve got here are a number of syntax errors, perhaps created by trying to translate the code.

Please post the actual view being used, without translating it or otherwise altering it.

you should show the full error log too.

Excuse me, I post the code in Italian
As an error it only reports to me that the Anagrafica field is a required field and must be filled in.
Maybe instead of enhancing the Master field in the view I have to insert a js every time I fill the fields Cognome and Nome

class Associati(models.Model):
    Anagrafica = models.CharField(max_length=50, blank=False, null=False)
    Cognome = models.CharField(max_length=20, blank=False, null=False)
    Nome = models.CharField(max_length=20, blank=False, null=False)

class AssociatiInseView(View):
template_name = ‘Pale/Tabelle/AssociatiInse.html’

def get(self, request):
    form = AssociatiForm()
    return render(request, self.template_name, {'form': form})
    def post(self, request):
        form = AssociatiForm(request.POST)
        if form.is_valid():
            associato = form.save(commit=False)
            # comune.Anagrafica = request.Anagrafica
            cognome = form.cleaned_data.get('Cognome', '')
            nome = form.cleaned_data.get('Nome', '')
            associato.Anagrafica = cognome + ' ' + nome
            # Quando non viene inserita la foto, memorizza il link al file di Base
            if 'Foto' in request.FILES:
                associato.Foto = request.FILES['Foto']
                # Se nessuna nuova immagine è stata fornita, mantieni il valore predefinito
                associato.Foto = 'Sito/Mamozio.png'
            # Aggiungi un messaggio di successo
            messages.success(request, f"ANAGRAFICA '{associato.Anagrafica}' - SALVATA ")
            # Azzerare i campi del form
            form = AssociatiForm()
            # Stampa tutti gli errori dei campi del form nel terminale
            for field, errors in form.errors.items():
                messages.error(request, f"Errore nel campo {field}: {', '.join(errors)}")
                print(f"Errore nel campo {field}: {', '.join(errors)}")
                print("Errore nel form. Controlla la console per dettagli.")
                # return HttpResponseBadRequest("Errore nel form. Controlla la console per dettagli.")

        # Redirect alla stessa pagina
        return redirect(reverse('AssociatiInse'))

To give it a try, I deleted the Cognome and Nome lines and inserted a def in the models, but the result does not change
I also entered a print and it displays the data

    def clean(self):
        cleaned_data = super().clean()
        cognome = cleaned_data.get('Cognome')
        nome = cleaned_data.get('Nome')
        cleaned_data['Anagrafica'] = f"{cognome} {nome}"
        print('Anagrafica ', cleaned_data.get('Anagrafica'))
        return cleaned_data

    def clean_Anagrafica(self):
        anagrafica = self.cleaned_data.get('Anagrafica')
        instance_being_edited = getattr(self, 'instance', None)

        if instance_being_edited and instance_being_edited.Anagrafica == anagrafica:
            return anagrafica

        if not anagrafica:
            raise forms.ValidationError("Questo campo è obbligatorio.")

        if Associati.objects.filter(Anagrafica=anagrafica).exists():
            raise forms.ValidationError("Anagrafica già presente. Inserisci un'altra Anagrafica.")

        return anagrafica

Please post the form you are using.

(Most likely, you do not want the Anagrafica field in the form if you are calculating its value.)

Meanwhile, I modified the Anagrafica field with these attributes and now it works

Anagrafica = models.CharField(max_length=50, *blank=True, null=True*)
    Last Name = models.CharField(max_length=20, blank=False, null=False)
    First Name = models.CharField(max_length=20, blank=False, null=False)

Yes, that corrects the error message you are encountering, but does it really satisfy the requirements of that field in the model? (You’re making changes to a model to resolve an issue with the form.)

I am not that knowledgeable about python but I get the impression that it performs the check on the required fields first and then goes on to check the clean functions.
But again it is just an impression

For the Form, yes. Not the model.

Don’t confuse a Django Form with a Model. They are two separate and distinct objects performing two separate sets of functions.

It’s the Form’s required fields being checked, not the Model’s.

If you are using a Model form (which you have not posted), you either don’t want to include the Anagrafica field at all (since it looks like you’re not using the input from it), or at least make it an optional field, or possibly even disabled.
But this work belongs in the form.
If your model design is such that Anagrafica must always have a value, then setting the model value to blank=True, null=True does not comply with your requirements.

The difference between Models and Form are clear to me, although I can use similar commands, see

Models con blank=False, null=False


Form con 'required': True

I agree that for Master Data it is not convenient to have blank=False nor "required": False

Keeping in mind the control sequence, which you indicated to me in other post, the first validation is in checking if the fields are required and then I can check the data with if form.is_valid(): where I can populate the Master field.
That said, it is not clear to me how to set the various files or how to populate the Master field before Saving
The best thing would be to populate it after entering the Cognome and after the First Nome, also as an effect would be better.
If you have any links you can point me to so I can go more in depth on this topic.
Sorry if I may have gotten some concepts wrong
Thanks for the explanations

The docs for The save() method show the technique of using commit=False when saving the form, to get the instance of the model. Once you have the model instance, you can update it - set whatever fields need to be set, and then save that instance. (The second example block in that section shows an example of it being done.)

Already tried but it always comes after if form is valid