variables as parameters in field options

I want to create a model, that will set editable=False on creation, and editable=True on editing item. I thought it should be something like this:

 home = models.ForeignKey(Team, editable=lambda self: True if self.id else False)

But it doesn't work. Maybe something with overriding the init can help me, but i don't sure what can do the trick. I know i can check for self.id in save() method, but is too late, i want this kind of logic in admin app when im filling the fields.


Asked by: Daniel834 | Posted: 01-10-2021






Answer 1

Add the following (a small extension of this code) to your admin.py:

from django import forms

class ReadOnlyWidget(forms.Widget):
    def __init__(self, original_value, display_value):
        self.original_value = original_value
        self.display_value = display_value

        super(ReadOnlyWidget, self).__init__()

    def render(self, name, value, attrs=None):
        if self.display_value is not None:
            return unicode(self.display_value)
        return unicode(self.original_value)

    def value_from_datadict(self, data, files, name):
        return self.original_value

class ReadOnlyAdminFields(object):
    def get_form(self, request, obj=None):
        form = super(ReadOnlyAdminFields, self).get_form(request, obj)
        fields = getattr(self, 'readonly', [])
        if obj is not None:
            fields += getattr(self, 'readonly_on_edit', [])

        for field_name in fields:
            if field_name in form.base_fields:
                if hasattr(obj, 'get_%s_display' % field_name):
                    display_value = getattr(obj, 'get_%s_display' % field_name)()
                else:
                    display_value = None

                form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name, ''), display_value)
                form.base_fields[field_name].required = False

        return form

You can then specify that certain fields should by readonly when the object is edited:

class PersonAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
    readonly_on_edit = ('home',)

admin.site.register(Person, PersonAdmin)

Answered by: Miller541 | Posted: 02-11-2021



Similar questions

python - Storing Data from both POST variables and GET parameters

I want my python script to simultaneously accept POST variables and query string variables from the web address. The script has code : form = cgi.FieldStorage() print form However, this only captures the post variables and no query variables from the web address. Is there a way to do this? Thanks, Ali


Python default values for class member function parameters set to member variables

I am running into a problem writing recursive member functions in Python. I can't initialize the default value of a function parameter to be the same value as a member variable. I am guessing that Python doesn't support that capability as it says self isn't defined at the time I'm trying to assign the parameter. While I can code around it, the lack of function overloading in Python knocks out one obvious solution I would t...


mysql - Python MySQLDB Insert with variables as parameters

I am using Python-MySQLdB library. I am trying to connect to the MySQL DB from a python script. I have a requirement where when the users register their account automatically the details should be added/saved to the MySQL DB. I'm trying to automate this feature using python. The script is running successfully and the values are not reflected in the DB. What might be the issue ?? This is the script....


python - Can I change function parameters when passing them as variables?

Excuse my poor wording in the title, but here's a longer explanation: I have a function which as arguments takes some functions which are used to determine which data to retrieve from a database, as such: def customer_data(customer_name, *args): # initialize dictionary with ids codata = dict([(data.__name__, []) for data in args]) codata['customer_observer_id'] = _customer_observer_ids(c...


python - How can I figure out which parameters map to which variables?

My life would be much easier if I could inspect what variables are assigned to what arguments. In the line: self.manager.addState("", [0,0]) # start with 2 empty buckets The addState method is defined in manager class as taking 2 parameters. It is called in the playGame method. I am having trouble understanding what parameters in th...


variables - change value of parameters of a function within the function python

I would like to define my function f(x,a) in which the value of 'a' changes, so that every time I call f(x,a), the value of 'a' will be different. So far the following code serve the purpose: a=0 def f(x): global a a=a+1 return a+x**2 In this case, everytime f(x) is called, the value of


python - Can we get request parameters from Django settings or other variables?

I see that the request parameters can be obtained in a viewset function using request variable. eg: @detail_route(methods=['get']) def mysampleviewsetfunction(self, request): print request But, I want to be able to access request from some common variable. The purpose of that is to write a common function that can be called from all viewsets. This common function should be able to a...


output - Python Print Variables with parameters

I know you can do this for a string: print("You have inputted {0} postive numbers and {1} negative numbers".format('3','2')) And this would produce: You have inputted 3 postive numbers and 2 negative numbers But I want to insert a letter in a variable name. For example, number = 4 print(nu{}ber.format("m")) And this should...


python - Why we use parameters in function when we can define variables in body of function?

I am confuse at this point , We use parameter in python suppose this program: method 1 def f(x,y): z=x+y print(z) f(1,2) and if we don't pass parameter and do calculation like this : method 2 def f(): x=1 y=2 z=x+y print(z) f() What is difference ,and Which one is good and why we pass parameter when we can use second metho...


Python Change Variables without Changing Parameters

Is there a way to change the variables z, a, b, c, and d without modifying the parameters of func1? The reason is that I'm trying to iterate from values 0 to 100 for z, a, b, c, and d to find an optimal / best solution to a problem I'm working on. However, normally, z, a, b, c, and d are constants. def func1(x, y): if x > z: return 0 if (x + y) > 0: return func2(x, y, a, c) ...


python - Django: Arbitrary number of unnamed urls.py parameters

I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this: /browse/<name1>/<value1>/<name2>/<value2>/ .... etc .... where 'name' maps to a model attribute and 'value' is the search criteria for that...


c# - How to analyse .exe parameters inside the program?

I have a program that can have a lot of parameters (we have over +30 differents options). Example: myProgram.exe -t alpha 1 -prod 1 2 -sleep 200 This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection ...


python - Default parameters to actions with Django

Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django? urlpatterns = patterns('',(r'^test/(?P<name>.*)?$','myview.displayName')) #myview.py def displayName(request,name): # write name to response or something I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving...


python - Loop function parameters for sanity check

I have a Python function in which I am doing some sanitisation of the input parameters: def func(param1, param2, param3): param1 = param1 or '' param2 = param2 or '' param3 = param3 or '' This caters for the arguments being passed as None rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to ...


python - How can I pass all the parameters to a decorator?

I tried to trace the execution of some methods using a decorator. Here is the decorator code: def trace(func): def ofunc(*args): func_name = func.__name__ xargs = args print "entering %s with args %s" % (func_name,xargs) ret_val = func(args) print "return value %s" % ret_val print "exiting %s" % (func_nam...


parameters - Python Newbie: Returning Multiple Int/String Results in Python

I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not sure what's the right solution, because integers and strings are not passed by reference but by value (at leas...


Print out list of function parameters in Python

Is there a way to print out a function's parameter list? For example: def func(a, b, c): pass print_func_parametes(func) Which will produce something like: ["a", "b", "c"]


python - How to create a decorator that can be used either with or without parameters?

I'd like to create a Python decorator that can be used either with parameters: @redirect_output("somewhere.log") def foo(): .... or without them (for instance to redirect the output to stderr by default): @redirect_output def foo(): .... Is that at all possible? Note that I'm not looking for a different solution to the problem of redirectin...


python - Scope of lambda functions and their parameters?

This question already has answers here:


sql - How do you make the Python Msqldb module use ? in stead of %s for query parameters?

MySqlDb is a fantastic Python module -- but one part is incredibly annoying. Query parameters look like this cursor.execute("select * from Books where isbn=%s", (isbn,)) whereas everywhere else in the known universe (oracle, sqlserver, access, sybase...) they look like this cursor.execute("select * from Books where isbn=?", (isbn,)) This means that if you ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top