On Tue, Jun 19, 2012 at 4:11 AM, Thomas Weholt <[email protected]> wrote:
> I want to make a few foreignkey-fields read-only in the admin after
> the post is saved, ie when the change-form for that item is opened
> after the item has been saved the two foreignkeys in question should
> not be editable. In my case the user has to chose two foreignkeys when
> first adding an entry, but those foreignkeys cannot be changed once
> the item has been saved. Is that possible?

Everything is possible - it's just a matter of how much code you have
to write :-)

In this case, there's no simple option to check to do what you
describe, but I can think of a couple of directions that might be
worth exploring. Roughly in increasing order of preference (i.e., 5 is
probably your best option, followed by 4, and so on):

1) Write a custom extension of ForeignKey that alters the available
choices based on whether the key already has a value.

2) Write a custom Form for the admin that restricts the available
choices, and install that Form in your ModelAdmin. Your form
constructor will need to contain logic something like the following:

if self.instance and self.instance.myfield:
    self.fields['myfield'].queryset =
MyObject.objects.filter(pk=self.instance.myfield.pk)

3) Override formfield_for_dbfield() on your ModelAdmin definition to
return a ModelChoiceField with restricted options if the foreign key
exists

4) Override formfield_for_choice_field() on your ModelAdmin definition
to restrict the list of choices.

5) Override get_readonly_fields() to make the foreign key a readonly
field if the foreign key has been defined.

You're going to need to do some experimentation, but hopefully this
has given you some ideas on where to start tinkering.

Yours,
Russ Magee %-)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to