Automatically create a model when another with ForeignKey is created

I'm trying to create a registration process where a certain model (Member) is automatically created when I create the model UserFields, but I'm unable to find a solution; this is what I tried:

class Member(models.Model):
    member_id = models.AutoField(primary_key=True)
    user_creation_date = models.DateField(auto_now_add=True)

class MemberType(models.Model):
    type_name = models.CharField(max_length=255, primary_key=True)
    member_type = models.ForeignKey(Member, on_delete=models.CASCADE)

class MemberFields(models.Model):
    member = models.ForeignKey(Member, on_delete=models.CASCADE)
    social_security_id = models.CharField(max_length=255)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    birth_date = models.DateField()
    birthplace = CountryField()
    gender = models.CharField(choices=GENDER_CHOICES, max_length=255)
    admission_date = models.DateField()

class MemberFieldsForm(forms.ModelForm):
    class Meta:
        model = MemberFields
        fields = [
        labels = {
            "social_security_id": "SSN",
            "first_name": "First name",
            "last_name": "Last name",
            "birth_date": "Date of birth",
            "birthplace": "Place of birth",
            "sex": "Sex",
            "address": "Address",
            "admission_date": "Admission date",
        widgets = {
            "member_type": forms.TextInput(attrs={'class': 'form-control'}),
            "social_security_id": forms.TextInput(attrs={'class': 'form-control'}),
            "first_name": forms.TextInput(attrs={'class': 'form-control'}),
            "last_name": forms.TextInput(attrs={'class': 'form-control'}),
            "birth_date": forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            "birthplace": forms.Select(attrs={'class': 'form-control'}),
            "address": forms.Select(attrs={'class': 'form-control'}),
            "sex": forms.Select(attrs={'class': 'form-control'}),
            "admission_date": forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            "member_type": forms.Select(attrs={'class': 'form-control'}),

def index(request):
    if request.method == 'POST':
        form = MemberFieldsForm(request.POST)
        if form.is_valid():
            c = form.changed_data["Member"]
            member = Member.objects.filter(name=c).first()
            if not member:
                member = Member.objects.create(name=c)
            MemberFields =
            MemberFields.Member = Member
            return HttpResponse("Member registered")
        form = MemberFieldsForm()
    return render(request, 'add-member.html', {'form': form})

I don't know if it's the right way to do it, I'm new to Django and Python and there are many things that are still unclear to me.

Thanks in advance!

Back to Top