Django中全局变量的替代方案?

时间:2012-12-21 15:41:26

标签: python django django-admin global-variables

我需要一种方法来修改另一个ModelAdmin中的一个ModelAdmin成员变量。所以我可能会使用全局变量。但是,如果有多个用户同时使用该应用程序,那么全局变量将继续意外地改变,并且所有地狱都会破裂。

Django中是否有任何方法允许我从另一个ModelAdmin修改一个ModelAdmin成员变量?

或者我犯了设计错误?我是否比实际更难,或者我错过了什么?那么使用线程和锁呢?消息传递???活动?!?!?!帮助


这是整个故事。我的应用程序允许用户通过选择兼容的CPU,主板,内存和硬盘驱动器(按此顺序)构建PC。通过选择CPU,它们仅限于带有CPU插槽的主板。通过选择DDR3 dimms的主板,它们仅限于DDR3内存,依此类推。

另外,感觉每个系统可以有许多相同的部分(例如:内存模块,但它们必须相同),我必须创建ManyToManyField关系并指定中间表(带有额外的count字段)through arg。这要求使用InlineAdmin模型在管理页面中显示字段。

令我高兴的是,raw_id_field变量导致下拉窗口小部件被一个按钮替换,该按钮弹出与change_list.html相同的表单,并允许用户过滤/排序/搜索他们想要的部分。然而,这对我的老板来说还不够好。现在我需要根据之前的选择预定义这些过滤器(即在选择带DDR3的主板后过滤内存与DDR3)。所以我对此表示赞赏:Default filter in Django admin但我需要一种方法来根据他们做出的其他选择动态地设置CpuAdmin.default_filters PcAdmin

我的模型,仅包括一部分简洁模型:

# models.py
class CPU(Part):
    partNum = models.CharField(max_length=60)
    price = models.DecimalField(precision=2)
    socket = models.CharField(max_length=60)
    numCores = models.CharField(max_length=60)

class PC(models.Model):
    name = models.CharField(max_length=60)
    customer = models.CharField(max_length=60)
    cpuChoices = models.ManyToManyField(CPU, through='PcCpuChoice')
    memoryChoices = models.ManyToManyField(Memory, through='PcMemoryChoice')
    hardDriveChoices = models.ManyToManyField(HardDrive, through='PcHardDriveChoice')
    motherBoardChoices = models.ManyToManyField(MotherBoard, through='PcMotherboardChoice')

class PcCpuChoice(models.Model):
    pc = models.ForeignKey(PC, unique=False)
    cpu = models.ForeignKey(CPU, unique=False)
    count = models.IntegerField()

# admin.py
class PartAdmin(admin.ModelAdmin):
    class Meta:
        abstract = True
    search_fields = ['partNum', 'description', 'model']
    default_filter = []

    def changelist_view(self, request, extra_context=None):
        if not request.GET.has_key(self.default_filter[0]):
            q = request.GET.copy()
            q[self.default_filter[0]] = self.default_filter[1]
            request.GET = q
            request.META['QUERY_STRING'] = request.GET.urlencode()
        return super(PartAdmin,self).changelist_view(request, extra_context=extra_context)

class CpuAdmin(PartAdmin):
    list_filter = ['brand', 'socket', 'numCores', 'graphics']
    list_display = ('partNum', 'description', 'brand', 'model', 'markupPrice', 'clockSpeed', 'watts', 'voltage')
    default_filter = ['numCores','8'] # need to change this from PcAdmin!!!

class PcCpuInline(admin.TabularInline):
    model = PcCpuChoice
    extra = 1
    max_num = 1
    raw_id_fields = ['cpu']

class PcAdmin(admin.ModelAdmin):
    inlines = [PcCpuInline, PcMotherboardInline, PcMemoryInline, PcHardDriveInline]

admin.site.register(PC, PcAdmin)

2 个答案:

答案 0 :(得分:1)

这不是一个答案,而是一个正确方向的推动。

localglobal还有更多变量上下文。在您的情况下,上下文为userbuild(如果用户同时进行多个构建)。

请注意,changelist_view()方法需要request个对象。从这里你可以获得usersession(任意数量的东西悬挂在它上面),以及所有其他良好的状态信息。

进一步的观察:在一个多线程,多进程的Web环境中,从某种意义上来说,实际上没有“全局”用于思考它。虽然可能在这样的环境中创建“全局”(例如使用memcached),但您将不得不非常努力地工作。

答案 1 :(得分:0)

感谢@PeterRowell指出我正确的方向。我使用 django会话来存储过滤器,javascript向服务器发送请求以在加载表单时更新过滤器并在离开表单时删除它们,一些视图函数来处理这些请求,向模型添加了一个函数(请求作为参数),根据已保存的部分更新过滤器,并覆盖PartAdmin的changelist_view函数,以使用request.session中的过滤器修改查询串。这是很多不同文件中的很多代码,但是这里有一些亮点可以帮助那些寻找这样的解决方案的人:

问题中发布的所有模型都保持不变。

PC的观点:

def update_filters(request):
    try:
        # get POST data
        url = request.POST['form_url']
        id = url.split('/')[-2:-1][0]
        system_type = url.split('/')[-3:-2][0]

        if id is not "new":
            system_content_type = ContentType.objects.get(app_label="systems", model=system_type.rstrip('s'))
            system = system_content_type.get_object_for_this_type(id=id)
            system.set_filters(request)
        else:
            request.session['filters'] = ''
        return HttpResponse("Filters where updated.")
    except:
        return HttpResponse("Select a part and click 'Save and continue' to set the filters.")


def delete_filters(request):
    request.session['filters'] = ''
    return HttpResponse("Filters where deleted.")

以下是放置在change_form.html中的javascript(通过PcAdmin add_view和change_view函数中的extra_context参数添加)

    function post_to_url(path, params, method) {
        method = method || "post"; // Set method to post by default, if not specified.

        // The rest of this code assumes you are not using a library.
        // It can be made less wordy if you use one.
        var form = document.createElement("form");
        form.setAttribute("method", method);
        form.setAttribute("action", path);

        for(var key in params) {
            if(params.hasOwnProperty(key)) {
                var hiddenField = document.createElement("input");
                hiddenField.setAttribute("type", "hidden");
                hiddenField.setAttribute("name", key);
                hiddenField.setAttribute("value", params[key]);

                form.appendChild(hiddenField);
             }
        }

        var frame = document.createElement("iframe");
        frame.name="hidden-form";
        form.target="hidden-form";
        document.body.appendChild(form);
        document.body.appendChild(frame);
        form.submit();
    }

    // when they load the page, set the filters
    $(document).ready(function(){
        post_to_url("/quotegenerator/systems/update_filters/",{'form_url': document.URL});
    });

    // when they exit, delete the filter cookie
    window.onbeforeunload = function() {
        post_to_url("/quotegenerator/systems/delete_filters/", {});
    }

最后,添加到PartAdmin的函数:

    def set_filters(self, request):
            # query and get the parts
            try:
                    cpu = self.cpuChoices.get()
            except:
                    cpu = False
            try:
                    mobo = self.motherBoardChoices.get()
            except:
                    mobo = False
            try:
                    mem = self.memoryChoices.get()
            except:
                    mem = False
            try:
                    hdd = self.hardDriveChoices.get()
            except:
                    hdd = False

           # for each combo of parts, figure out whats required
            # no parts at all
            if not (mobo or cpu or mem or hdd):
                    request.session['filters'] = ''
            # mobo only
            elif mobo and not (cpu or mem or hdd):
                    request.session['filters'] = 'socket='+mobo.socket
            # cpu only
            elif cpu and not (mobo or mem or hdd):
                    request.session['filters'] = 'socket='+cpu.socket
            # memory only
            elif mem and not (mobo or cpu or hdd):
                    request.session['filters'] = 'memType='+mem.memType
            # hard drive only
            elif hdd and not (mobo or cpu or mem):
                    request.session['filters'] = 'interface='+hdd.interface
            # mobo and cpu
            elif mobo and cpu and not (mem or hdd):
                    request.session['filters'] = 'memType='+mobo.memType+'&interface='+mobo.interface
            # mobo and memory
            elif mobo and mem and not (cpu or hdd):
                    request.session['filters'] = 'socket='+mobo.socket+'&interface='+mobo.interface
            # mobo and hd
            elif mobo and hdd and not (cpu or mem):
                    request.session['filters'] = 'socket='+mobo.socket+'&memType='+mobo.memType
            # cpu and mem
            elif cpu and mem and not (mobo or hdd):
                    request.session['filters'] = 'socket='+cpu.socket+'&memType='+mem.memType
            # cpu and hd
            elif cpu and hdd and not (mobo or mem):
                    request.session['filters'] = 'socket='+cpu.socket+'&interface='+hdd.interface
            # memory and hd
            elif mem and hdd and not (mobo or cpu):
                    request.session['filters'] = 'memType='+mem.memType+'&interface='+hdd.interface
            # mobo cpu and mem
            elif cpu and mobo and mem and not hdd:
                    request.session['filters'] = 'interface='+mobo.interface
            # mobo cpu and hd
            elif mobo and cpu and hdd and not mem:
                    request.session['filters'] = 'memType='+mobo.memType
            # mobo hd and mem
            elif mobo and mem and hdd and not cpu:
                    request.session['filters'] = 'socket='+mobo.socket
            # cpu mem and hd
            elif cpu and mem and hdd and not mobo:
                    request.session['filters'] = 'socket='+cpu.socket+'&memType='+mem.memType+'&interface='+hdd.interface
            # all parts
            else:
                    request.session['filters'] = ''

哦,PartAdmin的changelist_view函数确实发生了一些变化:

def changelist_view(self, request, extra_context=None):
    if ('filters' in request.session):
        q = request.GET.copy()
        for filter in request.session['filters'].split('&'):
            key, value = urllib.splitvalue(filter)
            # check if the request does not already use the filter
            # and that the model has the attribute to filter for
            if (not request.REQUEST.has_key(key)) and (key in self.list_filter):
                q[key] = value
        request.GET = q
        request.META['QUERY_STRING'] = request.GET.urlencode()
    return super(PartAdmin,self).changelist_view(request, extra_context=extra_context)