1 回答
TA贡献1842条经验 获得超21个赞
在您看来,您应该传递用户的主键,因此:
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(CalendarEventAdd, self).get_form_kwargs()
kwargs['user_id'] = self.request.user.pk
return kwargs
您可以将其保存在EventForm对象中:
class EventForm(forms.ModelForm):
def __init__(self, *args, user_id=None, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
self.user_id = user_id
# input_formats parses HTML5 datetime-local input to datetime field
self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',)
self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',)
def clean(self, *args, **kwargs):
form_start_time = self.cleaned_data.get('start_time')
form_end_time = self.cleaned_data.get('end_time')
form_manage_id = self.cleaned_data.get('manage_id')
between = Event.objects.exclude(pk=self.instance.pk).filter(
manage_id=self.user_id,
end_time__gte=form_start_time,
start_time__lte=form_end_time
)
if between.exists():
raise forms.ValidationError('Already Calendar entry for this time')
return super().clean()
如果您稍后决定不仅使用 来创建.exclude(pk=self.instance.pk)对象,还使用来更新对象,则 将会排除您正在编辑的对象。EventFormEvent
注意:文档建议使用AUTH_USER_MODEL
设置 [Django-doc]而不是 get_user_model()
[Django-doc]。这更安全,因为如果身份验证应用程序尚未加载,设置仍然可以指定模型的名称。因此最好这样写:
from django.conf import settings
class Event(models.Model):
# …
manage = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
添加回答
举报