[Fixed]-Add Foreign Model in other form model – Django 1.8

1πŸ‘

βœ…

The problem is this line in your form

self.fields['linea'] = linea

It doesn’t make sense to replace the field with a queryset or object like this.

Instead, exclude the field from your form

class AgregarActividad(forms.ModelForm):

    class Meta:
        model = Actividad
        fields = '__all__'
        exclude = ['updated', 'linea']

In the view, assign the object before saving. Note you should use get() instead of filter() to fetch a single object.

linea =  Linea.objects.get(pk=pk)

if request.method == "POST":
    form = AgregarActividad(request.POST, linea = linea)
    if form.is_valid():
        actividad = form.save(commit=False)
        actividad.linea = linea
        actividad.save()
        return redirect('/lineas/lista')
πŸ‘€Alasdair

Leave a comment