我注意到我的一个使用 apache/mod_wsgi 运行的 Django 应用程序有一种奇怪的行为。有一个屏幕显示一个表单,基本上是一个下拉列表,其中包含可安排给定站点的可用性列表,根据给定的每周容量(3 个站点/周)与给定已安排的站点总数之间的差异计算得出周。
此表单(ScheduleForm)是从以下 View (followup/views.py)呈现的:
def schedule(request, site_id):
site = Site.objects.get(pk=site_id)
if request.method == 'POST':
form = ScheduleForm(request.POST)
if form.is_valid():
(year, week) = request.POST['available_slots'].split('/')
site.scheduled = week2date(int(year), int(week[1:]))
site.save()
return HttpResponseRedirect('/stats/')
else:
form = ScheduleForm()
return render_to_response('followup/schedule_form.html',{
'form': form,
'site': site
}, context_instance=RequestContext(request))
这是表单类(followup/forms.py):
class ScheduleForm(forms.Form):
"""
Temporary lists
"""
schedules = Site.objects.filter(
scheduled__isnull=False
).values('scheduled').annotate(Count('id')).order_by('scheduled')
integration = {}
available_integration = []
# This aggregates all schedules by distinct weeks
for schedule in schedules:
if schedule['scheduled'].strftime('%Y/W%W') in integration.keys():
integration[schedule['scheduled'].strftime('%Y/W%W')] += schedule['id__count']
else:
integration[schedule['scheduled'].strftime('%Y/W%W')] = schedule['id__count']
for w in range(12): # Calculates availability for the next 3 months (3months*4 weeks)
dt = (date.today() + timedelta(weeks=w)).strftime('%Y/W%W')
if dt in integration.keys():
capacity = 3-integration[dt]
else:
capacity = 3
if capacity>0:
available_integration.append([dt, capacity])
"""
Form
"""
available_slots = forms.ChoiceField(
[[slot[0], '%s (%s slots available)' % (slot[0], slot[1])] for slot in available_integration]
)
class IntegrateForm(forms.Form):
integrated_on = forms.DateField(widget=AdminDateWidget())
这实际上工作得很好,但唯一的问题是,安排站点时,可用性列表不会刷新,除非我每次安排站点时都重新启动 apache 进程。
这就好像可用性列表将被表单类缓存...
任何想法都会受到热烈欢迎。预先感谢您提供的任何帮助。
最佳答案
这与 python 的工作方式有关,而不是 django。
下面这段代码
class ScheduleForm(forms.Form):
"""
Temporary lists
"""
schedules = Site.objects.filter(
scheduled__isnull=False
).values('scheduled').annotate(Count('id')).order_by('scheduled')
integration = {}
available_integration = []
仅在服务器启动时评估一次。
您不应该在类
级别上执行这些操作,而应在实例
级别上执行这些操作。
最有可能在表单的 __init__
方法中。
请参阅下面的示例:
关于Django 形成不刷新的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13305708/