我有这个ModelForm
class ScheduleForm(forms.ModelForm):
class Meta:
model = Schedule
fields = ['name', 'involved_people',]
def __init__(self, user, *args, **kwargs):
super(ScheduleForm, self).__init__(*args, **kwargs)
self.fields['involved_people'].queryset = Profile.objects.exclude(user=user)
这是我的观点
def create_schedule(request):
form = ScheduleForm(request.POST or None)
schedules = Schedule.objects.all().order_by('deadline_date')
if form.is_valid():
schedule = form.save(commit=False)
schedule.save()
messages.success(request, "Schedule added successfully!")
return render(request, 'schedule/index.html', {'schedules': schedules})
context = {'form': form}
return render(request, 'schedule/create_schedule.html', context)
如何在视图中传递 request.user
?
如何使用request.user
初始化表单?
答案 0 :(得分:3)
您已将user
添加到__init__
方法,
def __init__(self, user, *args, **kwargs):
所以现在你只需在实例化表单时将用户作为第一个参数传递。
form = ScheduleForm(request.user, request.POST or None)