gpt4 book ai didi

django - 如何在许多不同的 Django View 中注入(inject)相同的上下文?

转载 作者:行者123 更新时间:2023-12-01 17:19:19 24 4
gpt4 key购买 nike

我想在多个 View 中放置有关一个对象的信息,而不是在每个 View 的 get_context_data 中重复它。据您了解,我需要一个内部有 get_context_data 的类,我可以将其与其他 View 混合。在我的示例中,我希望在 UpdateAnotherObjectView 的上下文中看到“some_object”:

class BaseObjectInfoView(View):
def get_context_data(self, **kwargs):
context_data = super(BaseObjectInfoView, self).get_context_data(**kwargs)
context_data['some_object'] = SomeObjects.objects.get(pk=1)
return context_data

class UpdateAnotherObjectView(BaseObjectInfo, UpdateView):
template_name = 'create_object.html'
form_class = AnotherObjectForm
model = AnotherObjects

def get_context_data(self, **kwargs):
context_data = super(UpdateAnotherObjectView, self).get_context_data(**kwargs)
context_data['all_another_objects'] = AnotherObjects.objects.all()
return context_data

它可以工作,但 get_context_data 不是父“View”类的一部分。我可能需要从 BaseObjectInfoView 继承更多特殊的类吗?

或者也许用另一种方法构建上下文更好?

最佳答案

Mixin 不需要是 View ,但如果它们具有要重写的方法,它会对 IDE 有所帮助。

上下文由 django.views.generic.base.ContextMixin 处理(详细信息参见 this very handy site ),因此基于类的 View 方式如下:

from django.views import generic

class WebsiteCommonMixin(generic.base.ContextMixin):
page_title = ''
active_menu = None

def get_context_data(self, **kwargs):
context = super(WebsiteCommonMixin, self).get_context_data(**kwargs)
context.update(dict(page_title=self.page_title, active_menu=self.active_menu))
return context

class NewsListView(WebsiteCommonMixin, ListView):
page_title = 'News list'
active_menu = 'News'
model = News
paginate_by = 12

我对许多项目都这样做,并且您无论如何都必须创建的简单 View 是完全声明性的。简单地说,我的意思是它们可以由多个 mixins 组成,所有这些 mixin 都在 get_queryset、get_context_data 或 form_valid 中完成困难的工作。直接来自项目的更详细的示例:

class FeedbackMixin(object):
message = 'Well Done!'

def __init__(self):
self._message_kwargs = {}
super().__init__()

def add_message_kwarg(self, name, value) -> None:
self._message_kwargs[name] = value

def format_message(self, kwargs) -> str:
return self.message.format(**kwargs)

def generate_message(self) -> None:
msg = self.format_message(self._message_kwargs)
messages.success(getattr(self, 'request'), msg)


class ModelFeedbackMixin(FeedbackMixin, generic.edit.ModelFormMixin):
success_view_name = None
success_url_kwargs = None

def get_success_url_kwargs(self):
return self.success_url_kwargs

def get_success_url(self) -> str:
success_url_kwargs = self.get_success_url_kwargs()
if not self.success_view_name:
url = super().get_success_url()
elif success_url_kwargs is not None:
url = reverse(self.success_view_name, kwargs=success_url_kwargs)
else:
if hasattr(self.object, 'slug'):
url_kwargs = {'slug': self.object.slug}
else:
url_kwargs = {'pk': self.object.pk}
url = reverse(self.success_view_name, kwargs=url_kwargs)
return url

def form_valid(self, form):
response = super().form_valid(form)
self.generate_message()
return response

关于django - 如何在许多不同的 Django View 中注入(inject)相同的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44739145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com