I am trying to use Django to build up a model which can record the modification history of another user. Also, i used signal function to save the history model, when the parent model is saved. All other models works well.
The code is like below:
from control.model import DinningRoom`
class RecordDinningRoom(models.Model):
room = models.ForeignKey(DinningRoom)
datetime = models.DateTimeField('recordtime', auto_now=True)
TURN_ON_OFF = (
('ON', 'On'),
('OFF', 'Off'),
)
TEMP = (
('HIGH', 'High'),
('MEDIUM', 'Medium'),
('LOW', 'Low'),
)
on_off = models.CharField(max_length=2, choices=TURN_ON_OFF)
temp = models.CharField(max_length=2, choices=TEMP)
#signal function: if a user is created, add control livingroom to the user
def record_dinningroom(sender, instance, created, **kwargs):
#the object which is saved can be accessed with **kwargs
dinningroom = instance
record = RecordDinningRoom(on_off=dinningroom.on_off, temp=dinningroom.temp)
record.save()
# if created:
# RecordLivingRoom.objects.create(user=instance)
post_save.connect(record_dinningroom, sender=DinningRoom)
And when saving the foreign key model, it jumps to the error page with information "learning_record_recorddinningroom.room_id may not be NULL". I think it could be problems in either the room = models.ForeignKey(DinningRoom)
or the signal and record_dinningroom() function, but cannot figure out how to fix it.
You need to set room
for RecordDinningRoom
as it is not an optional field, try this:
record = RecordDinningRoom(
on_off=dinningroom.on_off,
temp=dinningroom.temp,
room=instance
)