这个问题和答案让我成功了 90%。所以感谢社区。
我有一个模型表单集,它验证并进入“如果有效”循环
模型.py
class session_log(models.Model):
anaesthetist_id = models.ForeignKey('auth.User')
session_start_datetime = models.DateTimeField(blank=False)
session_end_datetime = models.DateTimeField(blank=False)
session_type= models.ForeignKey(session_types, null=True, blank=True)
session_comments=models.TextField(null=True, blank=True)
def __unicode__(self):
return str(self.anaesthetist_id)+" "+str(self.session_start_datetime.date())+" "+str(self.session_type)
表格.py
class SessionList(forms.ModelForm):
session_comments = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':1}))
session_start_datetime = forms.DateTimeField(input_formats=['%d/%m/%y %H:%M',], widget=forms.DateTimeInput(format="%d/%m/%y %H:%M"))
session_end_datetime = forms.DateTimeField(input_formats=['%d/%m/%y %H:%M',], widget=forms.DateTimeInput(format="%d/%m/%y %H:%M"))
class Meta:
model = session_log
exclude = ('anaesthetist_id',)
fields = ['session_start_datetime', 'session_end_datetime', 'session_comments','session_type']
视图.py
def session_overview(request):
SessionListFormSet = modelformset_factory(session_log, form=SessionList, extra = 10, exclude =('anaesthetist_id',), can_delete=True)
x = session_log.objects.filter(anaesthetist_id=request.user.id).count()
y = x-10
initialformset = SessionListFormSet(queryset=session_log.objects.filter(anaesthetist_id=request.user.id).order_by("session_start_datetime")[y:])
if request.method == 'POST':
submitted_data = SessionListFormSet(data=request.POST)
if submitted_data.is_valid():
for session in submitted_data:
new_session = session.save(commit=False)
new_session.anaesthetist_id = request.user
new_session.save()
x 和 y 用于反转查询集并按降序给我最后 10 个结果,以便您在表单集的底部添加一个新会话,通常是后一个会话。这是一个风格的障碍
问题是,当我尝试保存或编辑表单时,我得到:
IntegrityError at /trainee/dataentry/
NOT NULL constraint failed: trainee_session_log.session_end_datetime
但我可以通过在保存循环中添加“如果不是无”来避免它:
boged views.py
if request.method == 'POST':
submitted_data = SessionListFormSet(data=request.POST)
if submitted_data.is_valid():
for session in submitted_data:
new_session = session.save(commit=False)
new_session.anaesthetist_id = request.user
if new_session.session_end_datetime is not None:
new_session.save()
我真的不知道为什么只有那个领域会导致问题。显然,这是一个完全错误
我真的很傻吗?