Home > database >  Why Django form.save() returns object(None)?
Why Django form.save() returns object(None)?

Time:02-05

from django.shortcuts import render
from django.forms import forms
from .models import Chart, ChartData
from .forms import ChartForm, ChartDataForm
import datetime

def home(request):
    chart_form = ChartForm(request.POST)
    chart_data_form = ChartDataForm(request.POST)
    context = {
        'chart_form': chart_form,
        'chart_data_form': chart_data_form,
    }
    if chart_form.is_valid():
        
        chart_obj = chart_form.save()
        chart = Chart.objects.get(pk=23)

        print(chart_obj)
        print(chart)

    
    return render(request, 'charts/home.html', context)

chart_form.save() returns "Chart object (None)

I have to eventually pass the chart_obj to another model for the foreign key, but right now it brakes there with error - save() prohibited to prevent data loss due to unsaved related object.

In the admin site I see that the object is created.

models.py below

import datetime
from django.db import models
from django.forms import DateTimeField

# Create your models here.

class Chart(models.Model):
    id = models.IntegerField(primary_key=True)
    type = models.CharField(max_length=10)
    chartname = models.CharField(max_length=20, null=True)
    
class ChartData(models.Model):
    dataY = models.IntegerField()
    dataX = models.DateTimeField()
    chart = models.ForeignKey(Chart, on_delete=models.CASCADE)

forms.py below

from django import forms
from .models import Chart, ChartData

class ChartForm(forms.ModelForm):
    class Meta:
        model = Chart
        fields = ['type','chartname']

class ChartDataForm(forms.ModelForm):
    class Meta:
        model = ChartData
        fields = ['dataY']

CodePudding user response:

You should use an AutoField to populate the model object when you save the object, so:

class Chart(models.Model):
    id = models.AutoField(primary_key=True)
    type = models.CharField(max_length=10)
    chartname = models.CharField(max_length=20, null=True)

or just without an id field:

class Chart(models.Model):
    type = models.CharField(max_length=10)
    chartname = models.CharField(max_length=20, null=True)

CodePudding user response:

Here you don't need to define the id explicitly, because Django does the same thing for you. If you want to rename the primary key to another thing, you can use the method below.

  •  Tags:  
  • Related