如何使用模型实例的一些参数初始化表单



我希望能够使用模型实例的组/用户手动发送短信/电子邮件通知。假设模型如下所示:

class Memo(models.Model):
title = models.CharField(max_length=100)
receiver = models.ManyToManyField(EmployeeType, related_name='memos_receiver')

我将对象实例传递给视图:

path('<int:pk>/notify', NotificationView.as_view(), name='memos-notify'),

形式和视图是我遇到麻烦的地方。我想我应该能够在视图中传递表单初始字段:

class NotificationView(FormView):
template_name = 'memos/notification_form.html'
form_class = MemoNotificationForm
success_url = reverse_lazy('overview')
def get_initial(self):
initial = super(NotificationView, self).get_initial()
memo = Memo.objects.filter(id=id)
initial['receiving_groups'] = memo.receiver.all()
return initial

表单如下所示:

class MemoNotificationForm(forms.Form):
class Meta:
fields = [
'receiving_groups'
]
receiving_groups = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple)

*注意:receiving_groups将是收到通知的人。一旦表格有效,我将应用send_sms方法发送它。

TypeError:int(( 参数必须是字符串、类似字节的对象或数字,而不是 'builtin_function_or_method'

是否需要初始化表单中的查询集?如果有人能清楚地描绘出这里的原因方式,将不胜感激。谢谢!

错误是由于这一行,

memo = Memo.objects.filter(id=id)

在这里,在你的范围内id成为python的内置功能,因此错误。要访问 URL 参数,您应该使用self.kwargs属性,如下所示

class NotificationView(FormView):
template_name = 'memos/notification_form.html'
form_class = MemoNotificationForm
success_url = reverse_lazy('overview')
def get_initial(self):
initial = super(NotificationView, self).get_initial()
memo = Memo.objects.filter(id=self.kwargs['pk'])
initial['receiving_groups'] = memo.receiver.all()
return initial

你可以在这里找到官方 Django 文档中的工作示例,动态过滤

最新更新