开发者

How to make a field non modifiable on edit page but able to create on add page?

开发者 https://www.devze.com 2023-02-10 02:56 出处:网络
I have a scenario given below: In my models.py class Room(models.Model): pop = models.ForeignKey(\'Pop\', verbose_name=\"POP\",

I have a scenario given below:

In my models.py

class Room(models.Model):
   pop = models.ForeignKey('Pop', verbose_name="POP",
                           help_text="Pop this room belongs to", null=True,
                           blank=True)
   .... other fields ....

 class Pop(models.Model):
    .... fields ....

In my admin.py

class RoomAdmin(admin.ModelAdmin):
    search_fields = [..some fields...]
    list_diplay = (pop, ....)
    ..... other configuration .....

Since Room has Foreign Key relationship with Pop, it is possible to associate multiple rooms with one Pop. I have to implement something like this.

  1. When the user clicks on the "Add Pop" link from the django admin page, the user should be allowed to associate multiple Room objects to a Pop object. But once Room objects have been associated to a Pop, it can neither be edited nor can it be associated with another Pop from the edit screen. Is it possible to achieve this?

I have these possible solutions but I don't know how to implement these ideas in Django or if these ideas are viable:

  1. CSS magic. I can associate a CSS id to pop field so that it can only be enabled for edit screens. I am not sure how to implement this

  2. Django's admin.py, If I could exclude pop field from th开发者_运维百科e edit screen, then it might work.

  3. Modify the templates so that they can support non editable fields.


Option 2 is the best. You can override the get_form method in your RoomAdmin class to exclude the pop field when there is an object to edit:

def get_form(self, request, obj=None, **kwargs):
    # if there's an object and it has been previously saved
    if obj is not None and obj.id is not None:
        # add 'pop' to the list of fields to exclude
        exclude = list(kwargs.get('exclude', []))
        exclude.append('pop')
        kwargs['exclude'] = exclude
    return super(RoomAdmin, self).get_form(request, obj, kwargs)
0

精彩评论

暂无评论...
验证码 换一张
取 消