GithubHelp home page GithubHelp logo

theatlantic / django-nested-admin Goto Github PK

View Code? Open in Web Editor NEW
703.0 44.0 99.0 3.37 MB

Django admin classes that allow for nested inlines

Home Page: http://django-nested-admin.readthedocs.org/

License: Other

Python 71.24% JavaScript 14.27% HTML 11.82% CSS 0.23% SCSS 2.44%
python django django-admin

django-nested-admin's Introduction

django-nested-admin

build_badge coverage_badge docs_badge

django-nested-admin is a project that makes it possible to nest admin inlines (that is, to define inlines on InlineModelAdmin classes). It is compatible with Django 3.2+ and Python 3.7+ and works with or without Grappelli. When Grappelli is not installed it allows Grappelli-like drag-and-drop functionality.

Installation

The recommended way to install django-nested-admin is from PyPI:

pip install django-nested-admin

Alternatively, one can install a development copy of django-nested-admin from source:

pip install -e git+git://github.com/theatlantic/django-nested-admin.git#egg=django-nested-admin

If the source is already checked out, use setuptools to install:

python setup.py develop

Configuration

To use django-nested-admin in your project, "nested_admin" must be added to the INSTALLED_APPS in your settings:

INSTALLED_APPS = (
    # ...
    'nested_admin',
)

If you’re using django-grappelli, you will also need to add to include nested_admin.urls in your urlpatterns:

urlpatterns = [
    # ...
    path('_nested_admin/', include('nested_admin.urls')),
]

Example Usage

In order to use django-nested-admin, use the following classes in place of their django admin equivalents:

django.contrib.admin nested_admin
ModelAdmin NestedModelAdmin
InlineModelAdmin NestedInlineModelAdmin
StackedInline NestedStackedInline
TabularInline NestedTabularInline

There is also nested_admin.NestedGenericStackedInline and nested_admin.NestedGenericTabularInline which are the nesting-capable versions of GenericStackedInline and GenericTabularInline in django.contrib.contenttypes.admin.

# An example admin.py for a Table of Contents app

from django.contrib import admin
import nested_admin

from .models import TableOfContents, TocArticle, TocSection

class TocArticleInline(nested_admin.NestedStackedInline):
    model = TocArticle
    sortable_field_name = "position"

class TocSectionInline(nested_admin.NestedStackedInline):
    model = TocSection
    sortable_field_name = "position"
    inlines = [TocArticleInline]

class TableOfContentsAdmin(nested_admin.NestedModelAdmin):
    inlines = [TocSectionInline]

admin.site.register(TableOfContents, TableOfContentsAdmin)

Testing

django-nested-admin has fairly extensive test coverage. The best way to run the tests is with tox, which runs the tests against all supported Django installs. To run the tests within a virtualenv run pytest from the repository directory. The tests require a selenium webdriver to be installed. By default the tests run with phantomjs, but it is also possible to run the tests with the chrome webdriver by passing --selenosis-driver=chrome to pytest or, if running with tox, running tox -- --selenosis-driver=chrome. See pytest --help for a complete list of the options available.

Contributing

This project uses webpack for building its javascript and css. To install the dependencies for the build process, run npm install from the root of the repository. You can then run npm run build to rebuild the static files.

License

The django code is licensed under the Simplified BSD License. View the LICENSE file under the root directory for complete license and copyright information.

django-nested-admin's People

Contributors

adamchainz avatar brandenhall avatar btknu avatar ctbarna avatar drikusroor avatar emdemir avatar fdintino avatar frnhr avatar hylje avatar joshmaker avatar kigawas avatar maldn avatar michael-k avatar oaklandpeters avatar obswork avatar olivierdalang avatar omni5cience avatar riconnon avatar safrone avatar sbussetti avatar sirspen avatar tari avatar whatisjasongoldstein avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-nested-admin's Issues

Add item does not show form

I have a nested inline and the links to add new items do nothing. True for both the parent and the child. Also weird is that I see twice the + graphic as so:

+ Add child
 +

+ Add parent
 +

Grapelli bug introduced at v2.2.0

Using Django 1.9 and Grapelli 2.8.1.

When updating to version >=2.2.0, I can no longer add instances of nested_admin objects (regardless of nesting depth). I click on "add object" but nothing happens. I also noticed a GUI change with this version, not sure if related.

Thanks!

Validate Formsets Using Variant of all_valid_with_nested

Great package! The grappelli integration is terrific.

I was playing with the nested inlines a couple levels deep and found a bug. Suppose the model is called TopLevel and the inlines are LevelOne, LevelTwo, and LevelThree as described in the usage at https://github.com/s-block/django-nested-inline.

If I try to create a LevelTwo item without creating a LevelOne item then I should get an error. With django-nested-inline it errors "Parent object must be created when creating nested inlines." using all_valid_with_nesting. But with django-nested-admin, a ValueError bubbles up on save stating that the foreign-key relationship is empty. It looks like you're using all_valid from django.forms.formsets and need to adopt the logic in django-nested-inline's all_valid_with_nesting.

Here's a link to the source: https://github.com/s-block/django-nested-inline/blob/master/nested_inline/admin.py#L127 I haven't the time for a pull request now (just scouting for a project) but I thought the bug report would be useful. There's a cryptic TODO comment in all_valid_with_nesting that may make sense to you.

Empty inline formsets are silently dropped instead of being saved

I have a 2 level nesting:

Admin

  • Inline 1
    -- Inline 2

If i use the "Add Inline 1" and do not enter any data ( checkboxes, textarea or inline2 items) and save the form, the inline 1 instance is not getting saved. Instead they are silently dropped. No error in the logs nor a ValidationError or some kind of User notification.

It only gets saved under following conditions:

  • if i tick any checkbox data in the inline1 formset it
  • if i add an inline2 item

Is this intended behaviour? How could i work around this limitation?

Empty extra inlines

nested-admin doesn't work correct with extra param, empty unchanged form raised validation errors and i must manually remove it

Tested with latest grappelli

Prepopulated Fields not Working on NestedInlines

It seems that both prepopulated_fields attriibute and get_prepopulated_fields() hook method do not trigger the JavaScript for it.

class CalculationFieldInline(nested_admin.NestedTabularInline):
    model = CalculationField
    prepopulated_fields = {'keyword': ('name',)}

    def get_prepopulated_fields(self, requests, obj):
        return {'keyword': ('name',)}

It works if I simply replace the NestedTabularInline to regular TabularInline in the code above.

'module' object has no attribute 'commit_on_success'

So I'm trying to use the nested admin tool. Upon installation, as soon as I put it in the list of installed apps and put in the URL route, I get the following errors when I try to run the server.

/Users/josh/Development/python/tutorial/lib/python2.7/site-packages/django/contrib/admin/util.py:7: RemovedInDjango19Warning: The django.contrib.admin.util module has been renamed. Use django.contrib.admin.utils instead.
  "Use django.contrib.admin.utils instead.", RemovedInDjango19Warning)

/Users/josh/Development/python/tutorial/lib/python2.7/site-packages/nested_admin/formsets.py:6: RemovedInDjango19Warning: django.contrib.contenttypes.generic is deprecated and will be removed in Django 1.9. Its contents have been moved to the fields, forms, and admin submodules of django.contrib.contenttypes.
  from django.contrib.contenttypes.generic import BaseGenericInlineFormSet

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/josh/Development/python/tutorial/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/josh/Development/python/tutorial/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/Users/josh/Development/python/tutorial/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/josh/Development/python/tutorial/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/Users/josh/Development/python/tutorial/lib/python2.7/site-packages/django/apps/config.py", line 86, in create
    module = import_module(entry)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/josh/Development/python/tutorial/lib/python2.7/site-packages/nested_admin/__init__.py", line 1, in <module>
    from .options import ModelAdmin, InlineModelAdmin, StackedInline, TabularInline
  File "/Users/josh/Development/python/tutorial/lib/python2.7/site-packages/nested_admin/options.py", line 52, in <module>
    transaction_wrap = getattr(transaction, 'atomic', transaction.commit_on_success)
AttributeError: 'module' object has no attribute 'commit_on_success'

Any idea what is going on here?

Nested Inline for a ManyToManyField

I'm getting 'app.Slot' has no ForeignKey to 'app.Intent_task'. error


class Task(models.Model):
    pass

class Intent(models.Model):
    task = models.ManyToManyField(Task)

class Slot(models.Model):
    intent = models.ForeignKey(Intent)

admin.py:

class TaskAdmin(nested_admin.NestedModelAdmin):
    inlines = [
        IntentInline
    ]

class IntentInline(nested_admin.NestedStackedInline):
    model = Intent.task.through  # see? another model, not Intent itself, and Slot is related exactly to Intent, not to each relation between Intent and Task
    inlines = [
        SlotInline
    ]

class SlotInline(nested_admin.NestedStackedInline):
    model = Slot

I see the reason, but can't figure out how to solve it, might be somehow related to get_queryset...

Requires Grappelli

It isn't documented, but the grp_tags library requires grappelli to be installed.

"Add link" shown when options "extra" and "max_num" equal 0

I've set options for my NestedTabularInline like this:

class PackageItemInline(nested_admin.NestedTabularInline):
model = PackageUnit
extra = 0
max_num = 0

But nothing changed, I still see "add link". Could anyone explain what the problem is ?

pypi update

Could Pypi be updated to the latest release?

https://pypi.python.org/pypi/django-nested-admin

The current release there (2.1.8) is incompatible with the latest Django releases (1.9.x) while 2.1.11 is.

Thanks for the package btw! The first to support all our use cases (3th we tried, ugh.. ).

'SlotInline' object has no attribute 'queryset'

I am using Django 1.8.1

Models:

class Profile(models.Model):
charge_by = models.CharField(max_length=16, choices=CHARGE_BY_CHOICES, blank=False, null=False)
valid_from = models.DateTimeField(blank=True, null=True)
valid_to = models.DateTimeField(blank=True, null=True)

class Slot(models.Model):
profile = models.ForeignKey(Profile)
start_time = models.TimeField()
end_time = models.TimeField()

class SlotSlab(models.Model):
slot = models.ForeignKey(Slot)
num_hours = models.SmallIntegerField(blank=False, null=False)
price = models.DecimalField(max_digits=10, decimal_places=2)

And in admin.py I have following

class SlotSlabline(NestedTabularInline):
model = SlotSlab

class SlotInline(NestedTabularInline):
model = Slot
inlines = [SlotSlabline,]

class ProfileAdmin(NestedModelAdmin):
inlines = [SlotInline,]

admin.site.register(Profile, ProfileAdmin)

But When I tried to create Profile getting error(Attached image):

'SlotInline' object has no attribute 'queryset'

screen shot 2015-07-22 at 8 17 19 am

save() prohibited to prevent data loss due to unsaved related object

Hello! First off, thanks for the great project.

Using:
django-1.9.7
django-nested-admin-3.0.5
django-grappelli-2.8.1

And with a quick contrived example app that looks like the following:

# models.py
class Main(models.Model):
    text = models.CharField(max_length=255, blank=True, null=True)

class Level1(models.Model):
    main = models.ForeignKey(Main)

class Level2(models.Model):
    level_1 = models.ForeignKey(Level1)
    text = models.CharField(max_length=255, blank=True, null=True)

# admin.py
class Level2InlineAdmin (nested_admin.NestedTabularInline):
  model = Level2
  extra = 0

class Level1InlineAdmin (nested_admin.NestedStackedInline):
  model = Level1
  extra = 0
  inlines = [ Level2InlineAdmin, ]

class MainAdmin (nested_admin.NestedModelAdmin):
  inlines = [ Level1InlineAdmin, ]

admin.site.register(Main, MainAdmin)
admin.site.register(Level1)
admin.site.register(Level2)

I get the error in the title the first time I attempt to create a Main item and add a Level2 item.

If I add a field of any type to Level1 and give it a value in the admin form, I am able to save the object and all subsequent modifications work. However, if I leave that hypothetical field blank I also get the same error.

It seems like there's a problem saving the intermediate Level1 model if the admin form didn't detect changes to that model specifically. Unfortunately I'm relatively new to Django, and am uncertain where to look for this kind of fix.

Please let me know if there's any more detail I can provide, or if I just have a fundamental misunderstanding of something :)

Thanks!

Is it possible to mix order of inlines?

I have models:

# models.py

class ParagraphTable(Paragraph):
    """Paragraph is just a model with GenericForeignKey field"""
    table = TableField()


class ParagraphImages(Paragraph):
    style = models.CharField(default='', max_length=255)


class ImageItem(models.Model):
    file = models.ImageField(upload_to='paragraph/images/%Y/%m/%d')
    parent = models.ForeignKey(ParagraphImages, on_delete=models.CASCADE)


class Node(models.Model):
    title = models.CharField(default='', max_length=255)

and admin:

# admin.py

class ImageInline(nested.NestedStackedInline):
    model = ImageItem
    extra = 0


class ParagrpaphImagesInline(nested.NestedGenericStackedInline):
    model = ParagrpaphImages
    sortable_field_name = 'order_weight'
    extra = 0
    inlines = [ImageInline]


class ParagraphTableInline(nested.NestedGenericStackedInline):
    model = ParagraphTable
    sortable_field_name = 'order_weight'
    extra = 0


class NodeAdmin(nested.NestedModelAdmin):
    inlines = [ImageStorageInline, ParagraphTableInline]
    weight_field_name = 'order_weight'

All works like a charm. Drag and drop support allows me sort my inlines under their parents.
So, I can change sort order between inlines of same type.

But UI allow drag and drop one of inlines under another type. In my case, I can drag ParagraphImages and drop among ParagraphTables. Actually, it is what I really need. But on save I'm getting "MultiValueDictKeyError" or "ManagementForm data is missing or has been tampered with".

Actually, I wrote same app for myself, but I didn't create nested feature and then I found this awesome package. And I solved the problem in a dummy-way, I just reorder back all inlines before save, and reorder on page load.

So, the question: Is it possible to use merged inlines sorted between their types?

===
The purpose of that behaivior is create "polymorphic" content types, there admin can add any inline in any order to build content page (like here: https://www.drupal.org/project/paragraphs)

Not all inlines get validated correctly.

I have nested admins set up as follows

class ServiceFormItemInline(GrappelliSortableHiddenMixin, NestedTabularInline):
    extra = 0
    sortable_field_name = 'order'


class ActivityChoiceInline(ServiceFormItemInline):
    fields = ('name', 'description', 'responsible', 'skip_numbering', 'people_needed', 'order')
    model = models.ActivityChoice


class ActivityInline(ServiceFormItemInline):
    fields = ('name', 'description', 'responsible', 'multiple_choices_allowed', 'skip_numbering', 'people_needed', 'order')
    model = models.Activity
    inlines = [ActivityChoiceInline]


class Level2CategoryInline(ServiceFormItemInline):
    fields = ('name', 'description', 'responsible', 'background_color', 'order')
    model = models.Level2Category
    inlines = [ActivityInline]


class Level1CategoryInline(ServiceFormItemInline):
    fields = ('name', 'description', 'responsible', 'background_color', 'order')
    model = models.Level1Category
    inlines = [Level2CategoryInline]

I have a problem that is illustrated in the figure below

selection_042

All empty 'name' fields should be given 'Required field' validation error. Two first levels seem to be working OK but from third nesting level it looks like that the first entry does not get validated at all.

Grappelli autocomplete field in nested inline got initialized twice if parent inline has autocomplete field with same name

As described, consider the case below:

class ChildInline(NestedStackedInline):
    fields = ('name', 'category')
    raw_id_fields = ('category',)
    autocomplete_lookup_fields = {'fk': ('category',)}

class ParentInline(NestedStackedInline):
    fields = ('name', 'category')
    inlines = (ChildInline,)
    raw_id_fields = ('category',)
    autocomplete_lookup_fields = {'fk': ('category',)}

the autocomplete field 'category' in ChildInline will be initialized twice, so that two input box will appear.
in DJNesting.initAutocompleteFields, $('#' + prefix + '-group > .djn-items > *:not(.djn-empty-form)') .find('input[name^="' + prefix + '"][name$="-' + this + '"]') will also find input in child inline with the same name.
currently, removing the 'category' field from autocomplete_loopup_fields in ChildInline seems ok.

Support NestedTabularInline (feature request)

Hi !

It would be awesome if it was possible to display the nested inlines using the tabular view as well. I tried to have a look at the code, but it's a bit over my competences :/

Bests,

Olivier

Suit works and looks OK - unless using tabs

Hi.
First of all - this is the first package that works on every django admin system i need - so really thanks for that. But for Django Suit there is a small issue. Suit has a features to use tabs and this does not work with this package.

As it states in documentation http://django-suit.readthedocs.io/en/develop/form_tabs.html#example classes for tabs are defined in property "suit_classes"

Problem is that HTML for nesting/admin/inlines - files stacked.html and tabular.html has no class "suit_classes".

{{ inline_admin_formset.opts.suit_classes }}

First div in Suit stacked
<div class="inline-group {{ inline_admin_formset.opts.suit_classes }}" id="{{ inline_admin_formset.formset.prefix }}-group">

First div in django-nested-admin stacked
<div class="inline-group group djn-group djn-stacked{% if is_nested %} djn-group-nested{% else %} djn-group-root{% endif %}"

I've seen there are some conditionals "ifsuit", "ifnosuit" in "common" view for standard admin and suit. But for grappelli there are different views. I did not make pull request with a fix because i don't know how you would like to organize this.

I hope my explanation is clear.

How does this project differ from django-nested-inline?

I've been using django-nested-inline for quite a while now and just stumbled on this project. It seems as though this project is still actively developed, which has attracted me to it. Is this project a fork of django-nested-inline, or is a completely different implementation? Due to the similarities in the project name, it might be worth devoting a small section of the readme to explaining the differences.

Deleting child not working

When I click the delete link of a child, this checks the parents checkbox for delete... If I click the checkbox of the child delete link, it checks and immediatly unchecks the checkbox of the parent.

Basically impossible to delete a child at the moment?

Multiplied inlines when ManyToManyField used

Models:

class One(models.Model):
    ...

class Two(models.Model):
  one = models.ForeignKey(One)

class Three(models.Model):
  two = models.ForeignKey(Two)
  additional = models.ManyToManyField(SomeModel)

Admin:

class OneAdmin():
    inlines = [TwoInline]

class TwoInline(nested_admin.NestedTabularInline):
    model = Two
    extra = 0
    inlines = [ThreeInline]

class ThreeInline(nested_admin.NestedStackedInline):
    model = Three
    extra = 0

Having above, I am selecting more than one additional in Django Admin. In result, Three model is multiplied by how many rows I have selected in additional. Is there any hack for that or it is a bug?

SSL Internal server error

We're using django-nested-admin and it seems to work fine except on our non-SSL site; when we try it there, we get the following error. We have configured the settings.py and urls.py as you've described here. The wsgi.py has the same permissions and content on both our ssl and non-ssl site. Do you have any ideas? Thanks! PS, we started out using nested-inlines, but we had the same problem there.

Target WSGI script '/apps/staging/wisdmepid/django_version/django_version/wsgi.py' cannot be loaded as Python module.

[Wed Nov 18 11:14:29.322753 2015] [:error] [pid 14068] [remote 128.173.38.156:104] mod_wsgi (pid=14068): Target WSGI script '/apps/staging/wisdmepid/django_version/django_version/wsgi.py' cannot be loaded as Python module.
[Wed Nov 18 11:14:29.322819 2015] [:error] [pid 14068] [remote 128.173.38.156:104] mod_wsgi (pid=14068): Exception occurred processing WSGI script '/apps/staging/wisdmepid/django_version/django_version/wsgi.py'.
[Wed Nov 18 11:14:29.322851 2015] [:error] [pid 14068] [remote 128.173.38.156:104] Traceback (most recent call last):
[Wed Nov 18 11:14:29.322873 2015] [:error] [pid 14068] [remote 128.173.38.156:104] File "/apps/staging/wisdmepid/django_version/django_version/wsgi.py", line 18, in
[Wed Nov 18 11:14:29.322955 2015] [:error] [pid 14068] [remote 128.173.38.156:104] application = get_wsgi_application()
[Wed Nov 18 11:14:29.322970 2015] [:error] [pid 14068] [remote 128.173.38.156:104] File "/apps/staging/wisdmepid/django_version/env/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application
[Wed Nov 18 11:14:29.323024 2015] [:error] [pid 14068] [remote 128.173.38.156:104] django.setup()
[Wed Nov 18 11:14:29.323034 2015] [:error] [pid 14068] [remote 128.173.38.156:104] File "/apps/staging/wisdmepid/django_version/env/lib/python2.7/site-packages/django/init.py", line 18, in setup
[Wed Nov 18 11:14:29.323096 2015] [:error] [pid 14068] [remote 128.173.38.156:104] apps.populate(settings.INSTALLED_APPS)
[Wed Nov 18 11:14:29.323107 2015] [:error] [pid 14068] [remote 128.173.38.156:104] File "/apps/staging/wisdmepid/django_version/env/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
[Wed Nov 18 11:14:29.323251 2015] [:error] [pid 14068] [remote 128.173.38.156:104] app_config = AppConfig.create(entry)
[Wed Nov 18 11:14:29.323266 2015] [:error] [pid 14068] [remote 128.173.38.156:104] File "/apps/staging/wisdmepid/django_version/env/lib/python2.7/site-packages/django/apps/config.py", line 86, in create
[Wed Nov 18 11:14:29.323374 2015] [:error] [pid 14068] [remote 128.173.38.156:104] module = import_module(entry)
[Wed Nov 18 11:14:29.323393 2015] [:error] [pid 14068] [remote 128.173.38.156:104] File "/usr/lib64/python2.7/importlib/init.py", line 37, in import_module
[Wed Nov 18 11:14:29.323448 2015] [:error] [pid 14068] [remote 128.173.38.156:104] import(name)
[Wed Nov 18 11:14:29.323471 2015] [:error] [pid 14068] [remote 128.173.38.156:104] ImportError: No module named nested_admin

max_num attribute issue

it seems that there is something wrong with the max_num. the maximum number of inlines to add is max_num +1.
to put it simply, if I set max_num to 3, then I can add 4 inlines totally.

ps. extra is set to 0, and is derived from NestedStackedInline

Nested many-to-many fields not working

I am running into a problem with the following models which nest many-to-many fields:

models.py

from django.db import models


class Part(models.Model):
    name = models.CharField(max_length=40)


class Component(models.Model):
    name = models.CharField(max_length=40)
    parts = models.ManyToManyField(Part)


class Car(models.Model):
    name = models.CharField(max_length=40)
    components = models.ManyToManyField(Component)

admin.py

from django.contrib import admin
import nested_admin

from .models import Part, Component, Car


class PartInline(nested_admin.NestedTabularInline):
    model = Component.parts.through


class ComponentInline(nested_admin.NestedTabularInline):
    model = Car.components.through
    exclude = ('parts',)
    inlines = (PartInline,)


@admin.register(Car)
class CarInline(nested_admin.NestedModelAdmin):
    exclude = ('components',)
    inlines = (ComponentInline,)

When I attempt to create a car in the admin, I end up with the following error:

ValueError at /admin/app/car/add/
'app.Component_parts' has no ForeignKey to 'app.Car_components'.

Am I doing something wrong or is this a bug?

nested inline saving error

when this package is used with grappelli 2.7.2, django 1.8.3, python 3.5, it is not possible to save a nested inline. instead it overrides the value of the field with (supposedly) the id number. see snapshot below;

schermafbeelding 2015-11-09 om 20 09 59

anyone else noticed this issue?

Multiple inlines rendered for a single model when that model has another Many-to-Many relationship

models.py

The team model can be assigned with a generic relationship to another model.

class Team(models.Model):
    name = models.CharField(max_length=100)
    # Generic relationship
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    class Meta:
        ordering = ['name']


class TeamRole(models.Model):
    role = models.ForeignKey(Role)
    team = models.ForeignKey(Team)
    members = models.ManyToManyField(User, blank=True)

    class Meta:
        ordering = ['team', 'role', 'members__first_name', 'members__last_name']

admin.py

class TeamRoleInline(nested_admin.NestedTabularInline):
    model = TeamRole
    extra = 0
    filter_horizontal = ['members', ]

class TeamInline(nested_admin.NestedGenericStackedInline):
    model = Team
    extra = 0
    inlines = [TeamRoleInline, ]

However, when adding multiple members to a TeamRole, multiple inline rows are rendered for that team role:

screenshot

In my serializer, to get around this issue:

class TeamListSerializer(serializers.ModelSerializer):
    roles = serializers.SerializerMethodField()

    class Meta:
        model = Team

    def get_roles(self, obj):
        return TeamRoleListSerializer(
            obj.teamrole_set.order_by('pk').distinct('pk'), many=True).data

DateTime shortcuts don't work when adding another inline

I already shared this issue in the last one, but because it is a separate issue, I'll add it here. When adding a new inline, if it has a DateTime field, the shortcuts don't work, instead just jumping you up to the top of the page. I'm pretty sure this is because adding a new inline essentially copies and pastes the template and then changes the id and name values, but it doesn't re-register the shortcuts to the new ids.

This doesn't seem like a hard fix and it really isn't a huge issue. If you want I can dig into it more and probably find a solution.

Fix adding ForeignKey instance to inline model

Many thanks for great app for the createing of nested inlines!

I use Django==1.8.4 and now I get some bugs with the adding of ForeignKey values in inline model. Whan I add another inline object I cannot add new foreign key item (only select and change selected item). For test may use follow models:

# models.py
class OtherModel(models.Model):
    field = models.CharField(max_length=4)

class Main(models.Model):
    field = models.CharField(max_length=4)

class Level1(models.Model):
    field = models.CharField(max_length=4)
    other_model = models.ForeignKey(OtherModel, null=True, blank=True)
    main = models.ForeignKey(Main)

class Level2(models.Model):
    field = models.CharField(max_length=4)
    level_1 = models.ForeignKey(Level1)

# admin.py
@admin.register(OtherModel)
class OtherModelAdmin(admin.ModelAdmin):
    pass

class Level2Inline(NestedTabularInline):
    model = Level2
    extra = 0

class Level1Inline(NestedStackedInline):
    model = Level1
    inlines = (Level2Inline, )
    extra = 0

@admin.register(Main)
class MainAdmin(NestedModelAdmin):
    inlines = (Level1Inline, )

@admin.register(Level1)
class Level1Admin(admin.ModelAdmin):
    pass

@admin.register(Level2)
class Level2Admin(admin.ModelAdmin):
    pass

And if I click "Add another Level1" and click add OtherModel instance (I marked with red border):
test
then It is no effect. Field "Other model" is empty (without created other model instance).

P. S. In my screen I used djangocms_admin_style fro pretty admin view, but also there is a bug without djangocms_admin_style when I tested.

Is it possible to mix NestedGenericStackedInline and NestedStackedInline?

Is it possible to mix NestedGenericStackedInline and NestedStackedInline? e.g.,

class SectionInline(nested_admin.NestedStackedInline):
    model = Section
    extra = 0
    inlines = [ CheckInline, ]

class ChecklistInline(nested_admin.NestedGenericStackedInline):
    model = Checklist
    extra = 0
    readonly_fields = ('title',)
    inlines = [ SectionInline, ]

class EventAdmin(admin.ModelAdmin):
    list_display = ('number',)
    list_display_links = ('number',)
    inlines = [ ChecklistInline, ]

When saving model I get a MultiValueDictKeyError

I have the following code:

class AnswerNestedInline(NestedStackedInline):
    model = Answer
    extra = 0

class QuestionInline(NestedStackedInline):
    model = Question
    inlines = [AnswerNestedInline]
    extra = 0

    raw_id_fields = ('media',)
    autocomplete_lookup_fields = {
        'fk': ['media']
    }


class ActivityAdmin(NestedAdmin):
    inlines = [QuestionInline]
    list_display = ['name','published', 'public', 'created_by']

    def get_readonly_fields(self, request, obj=None):
        readonly = super(ActivityAdmin, self).get_readonly_fields(request, obj)
        if not request.user.has_perm('LMS.publish_activity'):
            readonly += ('published',)
       if not request.user.has_perm('LMS.change_public_status'):
           readonly += ('public',)
       return readonly

When saving the object in the admin I get MultiValueDictKeyError "u'questions-0-id'"

Cleaning field in second layer of nesting is not saved

If I use a setup something like below, my_sub_field is not saved with the cleaned value.

I've checked and it does run the clean code correctly but doesn't save.

It does save correctly for my_main_field so it only seems to be an issue when actually using nested inlines.

class AdminSubForm(forms.ModelForm):
    def clean_my_sub_field(self):
        return 'override value'

class AdminMainForm(forms.ModelForm):
    def clean_my_main_field(self):
        return 'override value'

class SubInline(nested.NestedStackedInline):
    model = SubModel
    form = AdminSubForm

class MainInline(nested.NestedStackedInline):
    model = MainModel
    form = MainForm
    inlines = [SubInline]

class TopModelAdmin(nested.NestedModelAdmin):
    inlines = [MainInline,]

Automatic extras on nested inlines causes field is required error

After playing around a bit, I noticed that if I create a top level inline and it has nested inlines, if the nested inlines have an extras value > 0, the extra inlines that are automatically there won't save the first time. All of their fields will be cleared and the "Field Is Required" error will show for all of the fields that are required on those extra inlines.

I was able to work around this by simply setting each inline to use have 0 extras and then just using the "add " buttons to add more. If my explanation wasn't clear enough, I can post a video of what is happening.

Legacy Django support?

What's the earliest version of Django I can find a version of this app for? I'm running a Django 1.5 installation (yes, I know), but would love this functionality. Thoughts?

`sortable_options` AttributeError under Django 1.10

I just tried upgrading Django to 1.10, and I'm getting the following error: 'EventInlineAdmin' object has no attribute 'sortable_options'. The traceback ultimately points to:

File ".../env/lib/python3.5/site-packages/nested_admin/nested.py" in inline_formset_data
  112.                 'sortableOptions': self.opts.sortable_options,

EventInlineAdmin is super simple and actually doesn't use this project:

class EventInlineAdmin(admin.TabularInline):
    model = Event
    extra = 0

This error is not present with Django 1.9.9.

Add ability to specify classes on admin inline fields (to collapse)

Hi !

This commit django/django@5399ccc (applied to Django 1.10) allows to collapse inlines exactly like regular formsets, just by adding classes=['collapse'] in the Inline class.

As nested inlines can be even longer than regular inlines, it would be really nice to have this feature in django-nested-admin too.

I tried to make it work (patched django with the commit above, and made the same changes to nested-admin's stacked and tabular templates). It's almost ok, but it breaks the ability to order the rows by drag&drop for tabular inlines nested in stacked inlines.

Thanks for the great work

Decimal values resetting

I have a simple model of an assessment and an assessment version. One assessment can have multiple versions. When I use the nested admin module the version control field is being reset on the UI to incrementing values starting at zero. I can set the values through the django shell so the model and DB appear to be set up correctly. I swapped back to the standard django admin and the values were stored and displayed as expected. Any idea what could be causing the issue?

DJANGO = 1.8
django-nested-admin = 3.0.2

# Model
class Assessments(models.Model): 
    """Assessments Table"""
    Assessment = models.CharField(max_length=100, blank=False)

    def __unicode__(self):
        return self.Assessment 

    class Meta: 
        ordering = ['Assessment']
        verbose_name_plural = "Assessments"

class AssessmentVersion(models.Model): 
    """Assessment Versions Table"""
    Assessment = models.ForeignKey('Assessments')
    Version = models.DecimalField(max_digits=4, decimal_places=2)
    Description = models.CharField(max_length=500, blank=True)

    def __unicode__(self): 
        return "{0} : {1}".format(self.Assessment, unicode(self.Version))

    class Meta: 
        ordering = ['Assessment','Version']
        verbose_name_plural="Assessment Version"


# Admin (swap for standard admin) 
class AssessmentVersionInLine(nested_admin.NestedStackedInline):
    model = AssessmentVersion 
    sortable_field_name = 'Version'
    extra = 0

class AssessmentAdmin(nested_admin.NestedModelAdmin):
    model = Assessments
    fieldsets = [
        (None,               {'fields': ['Assessment']}),
    ]
    sortable_field_name = 'Assessment'
    inlines = [AssessmentVersionInLine]
    extra = 0

No support for Django 1.7.x

Sadly, there's no support for latest Django version.



Request Method: GET
Request URL: http://***/nested_admin/server-data.js

Django Version: 1.7.1
Python Version: 2.7.3
Installed Applications:
('grappelli',
 'debug_toolbar',
 'django.contrib.auth',
 'django.contrib.admin.migrations',
 'django.contrib.admin',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'nested_admin')
Installed Middleware:
(u'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/home/***/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/***/local/lib/python2.7/site-packages/nested_admin/views.py" in server_data_js
  32.         mimetype='application/javascript')
File "/home/***/local/lib/python2.7/site-packages/django/http/response.py" in __init__
  318.         super(HttpResponse, self).__init__(*args, **kwargs)

Exception Type: TypeError at /nested_admin/server-data.js
Exception Value: __init__() got an unexpected keyword argument 'mimetype'

KeyError while set readonly_fields in second nested inline

When I try set readonly fields in second inline, the error comes:
Django Version: 1.8
Exception Type: KeyError
Exception Value: u"Key 'second_name' not found in 'SecondForm'"
Exception Location: /usr/local/lib/python2.7/dist-packages/django/forms/forms.py in getitem, line 167

Here is the code:

class SecondInLine(nested_admin.NestedStackedInline):
     model = Second
     extra = 1
#failes
    def get_readonly_fields(self, request, obj=None):
       if not request.user.is_superuser and request.user.is_staff:
            self.readonly_fields = Second._meta.get_all_field_names()
            return self.readonly_fields
    return self.readonly_fields

class FirstInline(nested_admin.NestedStackedInline):
    model = First
    extra = 1
    inlines = [
       SecondInLine,
    ]

 #works fine
    def get_readonly_fields(self, request, obj=None):
        if not request.user.is_superuser and request.user.is_staff:
           self.readonly_fields = First._meta.get_all_field_names()
           return self.readonly_fields
       return self.readonly_fields

class SomeAdmin(nested_admin.NestedAdmin):
   inlines = [
       FirstInline,
   ]

      #works fine
    def get_readonly_fields(self, request, obj=None):
        if not request.user.is_superuser and request.user.is_staff:
           self.readonly_fields = Some._meta.get_all_field_names()
           return self.readonly_fields
        return self.readonly_fields

Nested autocomplete lookups on ManyToMany display "?" for multiple items.

When Grappelli autocomplete lookups are used for a ManyToMany relation on a nested inline, a question mark ("?") appears in place of all items if there is more than one related item.

This appears to be a problem introduced with the fix for multiple autocomplete initialization. PR coming right up.

"Add new ..." does not work in 1.10.5

I just created a sample, clean project with django 1.10.5 and python 3.5 + django-nested-admin and I see that for both, the NestedStackedInline and the NestedTabularInline "Add new..." stopped working.
zrzut ekranu 2017-02-01 22 56 16

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.