我有一个非常简单的模型,但是无法解决与约束有关的错误
我有2个模型:Jours和Heures与OneToMany关系链接(一个Jours实例可以有多个Heures实例)
我有一个表格可以在Heures中添加记录,但是有一个我不明白的错误:
NOT NULL约束失败:crf_heu.date_id
models.py
class Jours(models.Model):
_safedelete_policy = SOFT_DELETE_CASCADE
jou_ide = models.AutoField(primary_key=True)
jou_dat = models.DateField("Date du pointage", null=True, blank=True)
log = HistoricalRecords()
class Meta:
db_table = 'crf_jou'
verbose_name_plural = 'Dates'
ordering = ['jou_ide']
def __str__(self):
return f"{self.jou_dat}"
class Heures(models.Model):
_safedelete_policy = SOFT_DELETE_CASCADE
heu_ide = models.AutoField(primary_key=True)
date = models.ForeignKey(Jours, on_delete = models.CASCADE)
heu_dat = models.TimeField("Heure du pointage", null=True, blank=True,auto_now_add=True)
heu_cod = models.IntegerField("Code employé", null=True, blank=True)
heu_com = models.CharField("Commentaires", max_length = 150, null=True, blank=True)
log = HistoricalRecords()
class Meta:
db_table = 'crf_heu'
verbose_name_plural = 'Heures'
ordering = ['heu_ide']
def __str__(self):
return f"{self.heu_dat}"
views.py
@login_required
def index(request):
if request.method == "POST":
form = HeuresForm(request, data=request.POST or None)
if form.is_valid():
heu_cod = form.cleaned_data['heu_cod'],
heu_com = form.cleaned_data['heu_com'],
date_id = Jours.objects.get(jou_dat = datetime.date.today()).jou_dat
form.save()
return redirect('home')
else:
form = HeuresForm(request)
return render(request, 'pointage/index.html', {'form': form})
forms.py
class HeuresForm(forms.ModelForm):
# surcharge méthode constructeur (__init__) pour avoir accès aux variables de sessions
# https://stackoverflow.com/questions/3778148/django-form-validation-including-the-use-of-session-data
def __init__(self, request, *args, **kwargs):
self.request = request
super(HeuresForm, self).__init__(*args, **kwargs)
class Meta:
model = Heures
fields = ('heu_cod','heu_com',)
heu_dat= forms.CharField(label ='Heure du pointage', widget=forms.TimeInput(),initial = datetime.datetime.now,)
heu_cod = forms.CharField(label ='Code employé', widget=forms.PasswordInput())
heu_com = forms.CharField(label ='Commentaires', widget=forms.TextInput())
You didn't specified here date = models.ForeignKey(Jours, on_delete = models.CASCADE)
为空,因此需要或允许它,或在表单上添加此字段:class HeuresForm(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
self.request = request
super(HeuresForm, self).__init__(*args, **kwargs)
gender = forms.ModelChoiceField(queryset=Heures.objects.all(),
to_field_name = 'date',
empty_label="Select heures")
class Meta:
model = Heures
fields = ('heu_cod', 'heu_com', 'gender)
heu_dat= forms.CharField(label ='Heure du pointage', widget=forms.TimeInput(),initial = datetime.datetime.now,)
heu_cod = forms.CharField(label ='Code employé', widget=forms.PasswordInput())
heu_com = forms.CharField(label ='Commentaires', widget=forms.TextInput())