--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a8fc7ec5-96a9-87f8-c3ba-f89312cdbad9%40dewhirst.com.au.
Hi,
First of all, you should type REC_FIELDS and CONS_FIELDS, in capitals, as these are constants (this is not a Python language requirement but widely used style, also suggested by PEP8 iirc).
Then, it seems to me that most of the times you don't need the "global" keyword in your code, because you aren't assigning to "receipt_fields". "receipt_fields" is a name that points to an array, and you are only manipulating the array to which "receipt_fields" is pointing, you aren't actually changing what the name is pointing to. For example:
def hello(field):
b = receipt_fields
b.remove(field)
This will effectively remove field from receipt_fields, because "b" and "receipt_fields" are names that point to the same thing.
There is one exception in your code: at some point you are assigning to "receipt_fields_ro" inside a method. In that case, the "global" statement is necessary. However, the code looks quite bad to me, but I'm not looking into it further in order to not cover too many issues in this discussion.
Regardless whether you need to use the "global" keyword or not, you are using global variables, and this is a bad idea. It will work in some cases but eventually it will cause you headaches when you are least expecting them. I think it will work as long as each Django processes is serving a single HTTP request at a time. But one day you will use gunicorn's gevent worker, or something that runs Django in threads instead of processes, or async, and you will be in a huge mess, because when two users access the site at the same time the Django thread that is serving one user will be altering the global variables that are being used by the Django thread serving the other user. It will be a real pain.
Besides that, this style is quite unusual.
As for a proper solution, I don't remember exactly how the admin works, but if you can verify that ReceiptAdmin is instantiated in each request (rather than when Django starts), then you can override its __init__() method and set the variables you need in the object:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.receipt_fields = REC_FIELDS[:]
...
If ReceiptAdmin is instantiated when Django starts and the same object is thus used for many requests, you could hijack the "request" object, which might not be the best solution but will work way better:
def get_queryset(self, request):
qs = super().get_queryset(request)
request.receipt_fields = REC_FIELDS[:]
...
Regards,
Antonis