English 中文(简体)
Django Inline ModelAdmin - set inline field from request on Save (setuser field auto) (save_formset vs Save_model)
原标题:Django InlineModelAdmin - set inline field from request on save (set user field automatically) (save_formset vs save_model)

我有两种模式,一个是主讲人,另一个是相关的斜体。 可以说,该图形可用于对模型进行说明,并且应当跟踪在行政管理用户进行变革时的滞后情况。 虽然这似乎很简单(实际上,在用户领域是主要模型的一部分时,该数字说明了这一点),但当外地在网上时,我似乎无法抓住这个例子。

我的目标是:

  1. User edits MainModel
  2. User adds an InlineModel, not filling in the user field
  3. User presses save
  4. Code fills in the user field for newly created InlineModel instances
  5. (Bonus! user field is readonly for existing instances and hidden for new inlines)

我的问题:

  1. Is this correct? Its too bas save_model isn t called for InlineModelAdmin instances
  2. Does doing it this way allow me to save without causing an error? (user is required, validation flags it)
  3. How can I hide the user input field for new inlines, and have it readonly for existing inlines?

我目前的想法如下:


#models.py
class MainModel(models.Model):
    some_info = models.IntegerField()

class InlineModel(models.Model):
    main = models.ForeignKey(MainModel)
    data = models.CharField(max_length=255)
    user = models.ForeignKey( auth.User )

#admin.py
class InlineModelInline(admin.TabularInline):
    model = InlineModel
    fields = ( data ,  user )
    #readonly_fields = ( data ,  user ) #Bonus question later

class MainModelAdmin(admin.ModelAdmin):
    list_display = ( id ,  some_info )
    inlines = [InlineModelInline]

    #def save_model(self, request, obj, form, change):
        #http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model
        #Only called for MainModel, not for any of the inlines
        #Otherwise, would be ideal

    def save_formset(self, request, form, formset, change):
        #http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_formset
        #Experimenting showd this is called once per formset (where the formset is a group of inlines)
        #See code block at http://code.djangoproject.com/browser/django/tags/releases/1.2.1/django/contrib/admin/options.py#L894
        if not isinstance(formset.model, InlineModel):
            return super(MainModelAdmin, self).save_formset(request, form, formset, change)
        instances = formset.save(commit=False)
        for instance in instances:
            if not instance.pk:
                instance.user = request.user
        instance.save()
        formset.save_m2m()
最佳回答

我已经解决了我的上半个问题:

def save_formset(self, request, form, formset, change):
    if formset.model != InlineModel:
        return super(MainModelAdmin, self).save_formset(request, form, formset, change)
    instances = formset.save(commit=False)
    for instance in instances:
        if not instance.pk:
            instance.user = request.user
        instance.save()
    formset.save_m2m()

现在对奖金行为感兴趣:

  1. 由于审定规则,在增加一条新线时需要选择用户。 我最好的猜测是不要将用户领域纳入我的InlineModelInline。 田径,但后来,这只胜数向作者展示了现有的Inline Model事例。 (Edit:在此处增加用户,使其仅读到现场。)

  2. (Edit) 我怎么能够使现有星号数据成为仅读数据,但在增加一条新线时仍然能够加以编辑?

问题回答

回答Bonus问题:“我是否能够使现有的星号使数据成为仅读数据,但在增加一条新线时仍然能够加以编辑?”

我对同一模式使用了两条线:

#admin.py
class InlineModelInline(admin.TabularInline):
    model = InlineModel
    extra = 1
    max_num = 1

#admin.py
class InlineModelExistingInline(admin.TabularInline):
    model = InlineModel
    readonly_fields = ( data ,  user ) #All Fields here except pk
    can_delete = False
    extra = 0
    max_num = 0

class MainModelAdmin(admin.ModelAdmin):
    ...
    inlines = [InlineModelInline, InlineModelExistingInline]
    ...




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签