Код, показанный ниже, предоставляет варианты, которые мне нужны для поля приложения, и варианты, которые мне нужны для поля attr при использовании Admin.
У меня проблема с полем attr в встроенной форме для уже сохраненных записей.Аттр, выбранный для сохраненных данных, отображается мелким шрифтом над полем, но не внутри самого поля.
#
МОДЕЛИ:
Class Vocab(models.Model):
entity = models.Charfield, max_length = 40, unique = True)
Class App(models.Model):
name = models.ForeignKey(Vocab, related_name = 'vocab_appname', unique = True)
app = SelfForeignKey('self, verbose_name = 'parent', blank = True, null = True)
attr = models.ManyToManyField(Vocab, related_name = 'vocab_appattr', through ='AppAttr'
def parqs(self):
a method that provides a queryset consisting of available apps from vocab,
excluding self and any apps within the current app's dependent line.
def attrqs(self):
a method that provides a queryset consisting of available attr from vocab
excluding those already selected by current app, 2) those already selected
by any apps within the current app's parent line, and 3) those selected by
any apps within the current app's dependent line.
Class AppAttr(models.Model):
app = models.ForeignKey(App)
attr = models.ForeignKey(Vocab)
#
ФОРМЫ:
from models import AppAttr
def appattr_form_callback(instance, field, *args, **kwargs)
if field.name = 'attr':
if instance:
return field.formfield(queryset = instance.attrqs(), **kwargs)
return field.formfield(**kwargs)
#
ADMIN:
необходимый импорт
class AppAttrInline(admin.TabularInline):
model = AppAttr
def get_formset(self, request, obj = None, **kwargs):
kwargs['formfield_callback'] = curry(appattr_form_callback, obj)
return super(AppAttrInline, self).get_formset(request, obj, **kwargs)
class AppForm(forms.ModelForm):
class Meta:
model = App
def __init__(self, *args, **kwargs):
super(AppForm, self).__init__(*args, **kwargs)
if self.instance.id is None:
working = App.objects.all()
else:
thisrec = App.objects.get(id = self.instance.id)
working = thisrec.parqs()
self.fields['par'].queryset = working
class AppAdmin(admin.ModelAdmin):
form = AppForm
inlines = [AppAttrInline,]
fieldsets = ..........
necessary register statements