Skip to content

Commit

Permalink
Fix admin forms
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon committed Dec 13, 2024
1 parent bfca408 commit c2089c0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
13 changes: 2 additions & 11 deletions tom_targets/admin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import functools
from django.contrib import admin
from .models import Target, TargetList, TargetExtra, PersistentShare
from .forms import PersistentShareForm
from .forms import AdminPersistentShareForm


class TargetExtraInline(admin.TabularInline):
Expand All @@ -21,21 +21,12 @@ class TargetListAdmin(admin.ModelAdmin):

class PersistentShareAdmin(admin.ModelAdmin):
model = PersistentShare
form = PersistentShareForm
form = AdminPersistentShareForm
raw_id_fields = (
'target',
'user'
)

def get_form(self, request, obj=None, change=False, **kwargs):
Form = super().get_form(request, obj=obj, change=change, **kwargs)
# This line is needed because the ModelAdmin uses the form to get its fields if fields is passed as None
# In that case, a partial will not work, so just return the base form. The partial is necessary to filter
# On the targets a user has access to.
if kwargs.get('fields') is None:
return Form
return functools.partial(Form, user=request.user)


admin.site.register(Target, TargetAdmin)

Expand Down
12 changes: 9 additions & 3 deletions tom_targets/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,21 +243,27 @@ class TargetMergeForm(forms.Form):
)


class PersistentShareForm(forms.ModelForm):
class AdminPersistentShareForm(forms.ModelForm):
destination = forms.ChoiceField(choices=[], label='Share Destination', required=True)
target = forms.IntegerField(label='Target ID', initial=0, required=True)

class Meta:
model = PersistentShare
fields = '__all__'

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['destination'].choices = get_sharing_destination_options()


class PersistentShareForm(AdminPersistentShareForm):
target = forms.IntegerField(label='Target ID', initial=0, required=True)

def __init__(self, *args, **kwargs):
try:
self.target_id = kwargs.pop('target_id')
except KeyError:
self.target_id = None
super().__init__(*args, **kwargs)
self.fields['destination'].choices = get_sharing_destination_options()
if self.target_id:
self.fields['target'].initial = self.target_id
self.fields['target'].disabled = True

0 comments on commit c2089c0

Please sign in to comment.