2

我注意到我的一个 Django 应用程序中有一个奇怪的行为,它使用 apache/mod_wsgi 运行。有一个屏幕显示一个表格,基本上是一个下拉列表,其中包含安排给定站点的可用性列表,根据给定的每周容量(3 个站点/周)与已安排在给定站点的总数之间的差异计算星期。

此表单 (ScheduleForm) 是从以下视图 (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 进程。

就像可用性列表将被表单类缓存一样......

任何想法都会受到热烈欢迎。提前感谢您的任何帮助。

4

2 回答 2

3

这与 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 = []

将只评估一次 - 当服务器启动时。

class你不应该在水平上做这些事情,而应该在instance水平上。很可能在__init__表单的方法中。

请参阅以下示例:

于 2012-11-09T09:56:43.607 回答
2

我已经修改了我的代码,现在它就像一个魅力:) 我在这里提供它,以防它帮助任何有类似问题的人。

class ScheduleForm(forms.Form):
    available_slots = forms.ChoiceField()

    def __init__(self, *args, **kwargs):
        super(ScheduleForm, self).__init__(*args, **kwargs)

        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])

        self.fields['available_slots'].choices = [[slot[0], '%s (%s slots available)' % (slot[0], slot[1])] for slot in available_integration]
于 2012-11-09T10:51:49.293 回答