class SearchResultsView(ListView(: 型号 = 用户 template_name = 'all_users/医生/搜索.html'
def get_queryset(self): # new
query = self.request.GET.get('q')
object_list = User.objects.filter(Q(username__icontains=query))
return object_list
class PostCreateView(LoginRequiredMixin, CreateView):
template_name = 'all_users/doctor/post_form.html'
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.object_list
return super().form_valid(form)
尝试在创建视图中添加获取上下文数据并传递给模板。
def get_context_data(self, **kwargs):
query = self.request.GET.get('q')
context['object_list'] = User.objects.filter(Q(username__icontains=query))
return context
或者在表单模板中添加带有搜索 URL 的操作属性的表单标记