Using Foreignkey to save to BD Django

Asked

Viewed 554 times

0

I cannot do Data’s relationship with Teacher, I have to save Teacher and pass his id to Data foreign key and save, when I execute the code id is not passed

Forms.py

class ProfessorForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ProfessorForm, self).__init__(*args, **kwargs)
        self.fields['nome'].widget.attrs['placeholder'] = 'Professor'

    class Meta:
        model = Professor
        fields = '__all__'

class DataForm(forms.ModelForm):

    class Meta:
        model = Data
        fields = '__all__'

py views.

def home(request):
    context = {}
    template_name = 'envelope/cad_professor.html'
    if request.method == 'POST':
        form = ProfessorForm(request.POST)
        data = DataForm()
        if form.is_valid():
            data.form = form
            form.save()
            data.save()
            context['success'] = True
            return redirect (views.home)
    else:
       form = ProfessorForm()
    context['form'] = form
    return render(request,template_name , context)

PROBLEM SOLVED

data.save()
new_form = form.save(commit = False)
new_form.data = data
new_form.save()
  • How are your models?

  • data.form = form is not how a relationship is made. Also you should explain in the question what is this model Data and what field is being related, the way it is is insufficient to solve your problem. Place at least the Data and Professor model fields so your question can be solved.

No answers

Browser other questions tagged

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