Django:如何使用DRY原则覆盖第三方视图?
我已经为一个功能创建了一个单独的应用程序,我计划使用这个第三方应用程序扩展这个功能,我不打算触碰它的代码 我想要扩展的视图,发布一个问题或获取一个表单供用户提问。 我想使用此视图发布一篇文章。它使用的形式是不同的 Psuedo代码如下:Django:如何使用DRY原则覆盖第三方视图?,django,django-views,Django,Django Views,我已经为一个功能创建了一个单独的应用程序,我计划使用这个第三方应用程序扩展这个功能,我不打算触碰它的代码 我想要扩展的视图,发布一个问题或获取一个表单供用户提问。 我想使用此视图发布一篇文章。它使用的形式是不同的 Psuedo代码如下: post_question_view(request) If user is authenticated and read only, redirect somewhere else. form = form.Askquestionform(r
post_question_view(request)
If user is authenticated and read only, redirect somewhere else.
form = form.Askquestionform(request.REQUEST) ( I would like to do form = form.AskArticleform())
If the request is post and form is valid, get clean data. (The article will include additional data)
If user is authenticated, draft a question and write the question to the database. Generate a new-question-posted signal and redirect. (I don't have to make any changes here I guess)
If user is not authenticated, create anonymous question, write it to the database and redirect to the login page.
If the request is get fill in the form intial and render to ask_question.html (I would like to render to ask_article.html)
大部分代码都有一些小的改动需要完成。我需要填补一些空白,并在现有代码中添加一些新的空白。
我如何使用干燥的Principle进行此操作
我将根据您的伪代码回答您的三个问题,
post\u question\u view
是一个老式的(非基于类的)Django视图,没有参数:
post\u question\u视图
没有任何参数来修改它的行为,比如使用不同的表单,那么装饰师就帮不上忙了我所说的有一个例外是基于技术性的。您可以使用Python的
inspect
模块在运行时获取代码中原始视图的源代码,然后在运行时在文本级别上修改代码,然后在运行时评估该代码以创建新视图。这在技术上是枯燥的,因为你没有在源代码中重复你自己,但这根本不是人们所说的枯燥,因为这是一个可爱的技巧,而不是使用合理的代码组织和架构来避免源代码重复。你真的应该发布一些真实的代码示例,因为选项可能会因第三方视图实现的不同而有所不同。您试图在此处描述的视图是由您编写的还是由第三方应用程序编写的?对于这种模棱两可的代码很难,你能更接近真实场景吗?源函数(你想要扩展的)是否有必要的形式参数来传递你想要的(例如不同的形式)?