首页 > 解决方案 > 模板的django更新部分动态发布模型保存而不重新渲染

问题描述

我的模板中有一个侧栏,其中包含三个事件列(全部、活动、非活动)。侧栏中项目的活动在后端控制。

我想动态更新(活动,非活动)下显示的事件列表,当它们的状态发生变化并保存到数据库中时。

我可以通过不断发出 Ajax 请求并根据视图的响应更新模板来做到这一点。

但我想知道是否可以使用 django 信号和 post_save 触发并更新模板上的项目。如果您需要更多详细信息,请告诉我。

代码片段:

<!-- sidebar -->
<div class="container">

    <div class="sidebar">
      <div class="side-filter-header">
        <a class="selected">All Events</a>
          <a class="" >Active Events</a>
          <a class="" >Inactive Events</a>
      </div>

      <div class="side-filter-list">

        <a href="#" class="list-group-item active-event">
            <ul>
              <li>Event 1</li>
            </ul>
        </a>

        <a href="#" class="list-group-item inactive-event">
          <ul>
            <li>Event 2 </li>
          </ul>
        </a>

        <a href="#" class="list-group-item inactive-event">
          <ul>
            <li>Event 3</li>
          </ul>
        </a>

      </div>
    </div>
</div>

Django 模型.py

class EventStatus(Enum):
    ACTIVE = "ACTIVE"
    INACTIVE = "INACTIVE"

class Event(models.model):
   eventNo = models.IntegerField()
   eventStatus = models.CharField(max_length=255, default=EventStatus.INACTIVE, choices=[(tag,tag.value) for tag in EventStatus])

Django 视图.py

def update_sidebar():
   event = Event.objects.filter().last() # example
   # some condition
   event.eventStatus = "ACTIVE"
   event.save()  # I want to trigger the view here. What would be the best and efficient way?

标签: pythondjango

解决方案


你可以这样做

def save(self, *args, **kwargs):
    event = Event.objects.filter().last() # example
    # some condition
    event.eventStatus = "ACTIVE"
    super().save(*args,**kwargs)

推荐阅读