我在基于类的视图(创建,更新,删除视图)中使用django-select2 在CreateView中,我在窗体视图中使用form_class。在这种形式下,我使用小部件来选择相关对象。而且我需要通过created_user(所有者)过滤这些对象。如何将方案中的当前用户传递给小部件ModelSelect2MultipleWidget类?
forms.py:
class AccountSearchFieldMixin(object):
search_fields = [
'login__icontains',
'password__icontains',
'phone__icontains',
]
class AccountSelect2TagWidget(AccountSearchFieldMixin, ModelSelect2MultipleWidget):
model = VkAccount
queryset = VkAccount.objects.exclude(proxy__isnull=True)
def create_value(self, value):
self.get_queryset().create(name=value)
class TaskVkInvitationsFriendsSearchForm(forms.ModelForm):
# country = ModelChoiceField(Countries.objects.all(), empty_label=None, label='Страна')f
class Meta:
model = TaskVkInvitationsFriendsSearch
exclude = ['type', 'date_creation', 'date_update', 'maintask', 'invited_friends']
widgets = {
'accounts': AccountSelect2TagWidget,
'cities': CitiesSelect2TagWidget,
'scheduler_data': forms.HiddenInput,
# 'country': CountrySelect2TagWidget
}
def __init__(self, *args, **kwargs):
self.owner = kwargs.pop('owner')
super(TaskVkInvitationsFriendsSearchForm, self).__init__(*args, **kwargs)
views.py:
class BaseTaskMixin:
model = TaskVkInvitationsFriendsSearch
form_class = TaskVkInvitationsFriendsSearchForm
success_url = reverse_lazy('vk_bot_tasks_list')
template_name = 'vk_bot/create_task.html'
class TaskCreateView(BaseTaskMixin, CreateView):
def form_valid(self, form):
model = form.save(commit=False)
t = Task()
t.save()
model.maintask = t
model.save()
form.instance.owner = self.request.user
return super(TaskCreateView, self).form_valid(form)
答案 0 :(得分:1)
我需要使用search_fields更改mixin并将其推送到data_view参数:
forms.py:
class AccountSearchFieldMixin(object):
search_fields = [
'login__icontains',
'password__icontains',
'phone__icontains',
]
def __init__(self, *args, **kwargs):
kwargs['data_view'] = 'account_json'
super(AccountSearchFieldMixin, self).__init__(*args, **kwargs)
创建带有select2的json答案请求的视图。
views.py:
class AccountJsonView(AutoResponseView):
def get_queryset(self):
qs = super().get_queryset()
return qs.filter(owner=self.request.user)
最后一次更改urls.py:
path('fields/account.json', login_required(views.AccountJsonView.as_view()), name="account_json"),