【问题标题】:Revert objects on site instead of admin using django simple history使用 django 简单历史恢复站点上的对象而不是管理员
【发布时间】:2017-11-24 00:57:50
【问题描述】:

我在管理站点上使用了 django 简单历史包,以便能够跟踪并恢复到模型对象的先前版本。我正在设计一个 Web 表单,允许用户使用 django 上的模型表单更改模型对象的实例,并希望允许用户查看并恢复到以前的版本。也让他们看到与当前版本相比有哪些变化。

通过下面的代码,我可以在 histoire 下的模板上获取历史记录列表。

class CompanyDetailView(LoginRequiredMixin,generic.DetailView):
    model = Company

    def get_context_data(self, **kwargs):
         context = super(CompanyDetailView, self).get_context_data(**kwargs)
         company_instance = self.object
         context['histoire'] = company_instance.history.all()
         return context

在我的模板中,

<p>
    Previous versions:
    {% for item in histoire %}
      <li>
        {{ item }} submitted by {{ item.history_user }}  {{
         item.history_object }}
      </li>
      {% endfor %}

</p>

但理想情况下,我希望 item.history_object 是一个链接,用户可以查看之前的对象并能够在需要时恢复。

【问题讨论】:

    标签: django python-3.x django-templates django-views django-simple-history


    【解决方案1】:

    我通过将 HistoricForm 添加到我的模型表单中做了类似的事情。

    class MyModelForm(HistoricForm, ModelForm):
         ...
    

    HistoricForm 需要额外的 history_id kwarg。 如果提供了history_id,HistoricForm 将ModelForm 实例与history_instance 交换(您的实例在history_id 时的样子)。这样,您的表单将显示对象的历史版本。

    class HistoricForm(object):
        def __init__(self, *args, **kwargs):
            self.history_id = kwargs.pop('history_id', None)
            instance = kwargs.get('instance')
            if instance and self.history_id:
                kwargs['instance'] = self.get_historic_instance(instance)
    
            super(HistoricForm, self).__init__(*args, **kwargs)
    
        def get_historic_instance(self, instance):
            model = self._meta.model
            queryset = getattr(model, 'history').model.objects
            historic_instance = queryset.get(**{
                model._meta.pk.attname: instance.pk,
                'history_id': self.history_id,
            }).instance
            return historic_instance
    

    如果没有提供 history_id,ModelForm 将照常工作。

    您可以通过显示历史实例并保存来还原(这样您将发布您的历史数据)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 2020-09-29
      • 1970-01-01
      相关资源
      最近更新 更多