0

I'm trying to a save a foreign key inside an object into my db using a form, but i get the error : 'Syntax isn't valid for integer', I discovered that postgreSQL save the foreign key as an id, how can i save it then?

Here it is my code.

Models.py :

class treballador(models.Model):
    nom = models.CharField(max_length=150, null=False, unique=True)
    cognom = models.CharField(max_length=150, null=False)
    tipusDocID = models.CharField(max_length=3, choices=TIPUSDOC, null=False)
    docId = models.CharField(max_length=9, null=False)
    tlf_regex = RegexValidator(regex=r'^\d{9,9}$',message="Phone number must be entered in the format: '+999999999'. Up to 9 digits allowed.")
    tlf = models.CharField(validators=[tlf_regex], blank=True, max_length=9)  # validators should be a list
    correu = models.EmailField(max_length=254)
    ciutat = models.CharField(max_length=150)
    dataDAlta = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return unicode(self.nom) or unicode(self.id)

class despesa(models.Model):
    nomTreballador = models.ForeignKey(treballador, to_field='nom')
    tipusDeGast = models.CharField(max_length=3, choices=GASTOS)
    quantia = models.DecimalField(max_digits=5, decimal_places=2)
    data = models.DateTimeField()

forms.py:

class desModelForm(forms.ModelForm):
    data = forms.DateField(widget=DateInput(format='%d/%m/%Y'), label="Data de la despesa", input_formats=['%d/%m/%Y'])

    class Meta:
        model= despesa
        fields= ["nomTreballador","tipusDeGast","quantia","data"]

        def clean_despesa(self):
            despeses = self.cleaned_data.get("tipusDeGast")
            return despeses

        def clean_date(self):
            date = self.cleaned_data.get("data")
            return date

        def clean_quantia(self):
            quantia = self.cleaned_data.get("quantia")
            return quantia

        def clean_nom(self):
            nomTreballador = self.cleaned_data.get("nomTreballador")
            return nomTreballador

    def __init__(self, *args, **kwargs):
        super(desModelForm, self).__init__(*args, **kwargs)
        self.fields["nomTreballador"].queryset=treballador.objects.all().distinct()

views.py:

def home(request):
    form = desModelForm(request.POST or None)

    context = {
        "gast_form": form
    }


    if form.is_valid():

        desp = form.save(commit=False)

        desp.save()



    return render(request, "imputacioDespeses.html", context)

2 Answers 2

1

Your foreign key field is the problem. Remove to_field and Django will automatically map it to ID

nomTreballador = models.ForeignKey(treballador)
Sign up to request clarification or add additional context in comments.

Comments

0

Remove to_field='nom' from the nomTreballador ForeignKey field and it will insert the Treballador's primary key (an integer) instead of nom (which is a string).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.