Skip to main content

Django application for GenericForeignKey

Project description

Description

‘django-generic-fk’ is essentially just a collection of widgets and mixin for easy use GenericForeignKey in Django admin.

Install

::

pip install generic-fk

Usage

Mixin

In file admin.py:

from django.contrib import admin

from apps.models import SomeModel
from generic_fk.mixins import ModelAdminMixin


class SomeModelAdmin(ModelAdminMixin, admin.ModelAdmin):
    pass

admin.site.register(SomeModel, SomeModelAdmin)

Widget

In file admin.py:

from django.contrib import admin
from django.contrib.admin.widgets import ForeignKeyRawIdWidget
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import ManyToOneRel
from django import forms

from apps.models import SomeModel
from generic_fk.widgets import ContentTypeSelect


class SomeModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SomeModelForm, self).__init__(*args, **kwargs)
        try:
            model = self.instance.content_type.model_class()
            model_key = model._meta.pk.name
        except (AttributeError, ObjectDoesNotExist):
            model = self.fields['content_type'].queryset[0].model_class()
            model_key = 'id'
        self.fields['object_id'].widget = ForeignKeyRawIdWidget(
            rel=ManyToOneRel(model, model_key),
            admin_site=admin.site
        )

    class Meta:
        model = SomeModel
        widgets = {
            'content_type': ContentTypeSelect
        }

class SomeModelAdmin(admin.ModelAdmin):
    form = SomeModelForm

admin.site.register(SomeModel, SomeModelAdmin)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

generic-fk-0.1.1.tar.gz (3.8 kB view details)

Uploaded Source

File details

Details for the file generic-fk-0.1.1.tar.gz.

File metadata

  • Download URL: generic-fk-0.1.1.tar.gz
  • Upload date:
  • Size: 3.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for generic-fk-0.1.1.tar.gz
Algorithm Hash digest
SHA256 bdfb362b1d9c1614d9f7653a62701a3f6623dd91bfccd9d9a2d907447d7ffcfe
MD5 dc6a1661171883858595d5bb21db10ee
BLAKE2b-256 a411a5c0e3cf26f4d0c8ba55a33c8bdca0b934d3388d4d0a5ed5352b7550b739

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page