Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to export Django queryset to csv file
I have a values queryset of my values. how can convert it to a csv file. Its important to export it by postgresql not python. because queryset have too many records. -
How to handle multiple notifications model in Django?
I'm trying to build website which monitor multiple websites for changes. For example - if keyword [XYZ] occurs on website A then send notification to user. Currently I'm stuck on adding more notification channels without creating mess in my code. I want to create a abstract class with args target, message, methods like send_message and then inherence from it to SMSNotification, PusherNotification, EmailNotification. Where should I put that logic into project? I was thinking about adding it to models.py, but I'm not sure if this won't cause troubles during further development. What's the proper approach for this? -
Django 1.11 Form multiple data submit in one execute
I have a form called shift here my forms.py class ShiftForm(forms.ModelForm): class Meta: model = Shift fields = '__all__' and have createview class for my shift here my views.py class ShiftCreateView(CreateView): fields = ('start', 'end', 'off_start', 'off_end', 'shift', 'employee') model = models.Shift and I already create the form template, like this. its work and the data was submitted to my database, imagine my database table like this: #table shift +---------------+---------------+---------------+---------------+------------+------------+-------------+ | start | end | off_start | off_end | time | user_id | shift_id | +---------------+---------------+---------------+---------------+------------+------------+-------------+ | 2018-01-01 | 2018-01-05 | 2018-01-06 | 2018-01-07 | 07:00 | 1 | 1 | | .... | .... | .... | .... | .... | .... | ... | +---------------+---------------+---------------+---------------+------------+------------+-------------+ my question is how to make it multiple in one form?... example like this: so on my database table will look like this in single submit. #table shift +---------------+---------------+---------------+---------------+------------+------------+-------------+ | start | end | off_start | off_end | time | user_id | shift_id | +---------------+---------------+---------------+---------------+------------+------------+-------------+ | 2018-01-01 | 2018-01-05 | 2018-01-06 | 2018-01-07 | 07:00 | 1 | 1 | | 2018-01-01 | 2018-01-05 | 2018-01-06 | 2018-01-07 | 07:00 | 1 | 2 | | 2018-01-01 | 2018-01-05 | 2018-01-06 | 2018-01-07 … -
link in html do not function (django)
python 2.7 DJANGO 1.11.14 win7 when I click the link in FWinstance_list_applied_user.html, it was supposed to jump to FW_detail.html, but nothing happened url.py urlpatterns += [ url(r'^myFWs/', views.LoanedFWsByUserListView.as_view(), name='my-applied'), url(r'^myFWs/(?P<pk>[0-9]+)$', views.FWDetailView.as_view(), name='FW-detail'), views.py: class FWDetailView(LoginRequiredMixin,generic.ListView): model = FW template_name = 'FW_detail.html' models.py class FW(models.Model): ODM_name = models.CharField(max_length=20) project_name = models.CharField(max_length=20) FW_detail.html {% block content %} <h1>FW request information: {{ FW.ODM_name}};{{ FW.project_name}}</h1> <p><strong>please download using this link:</strong> {{ FW.download }}</p> {% endblock %} FWinstance_list_applied_user.html {% block content %} <h1>Applied FWs</h1> {% if FW_list %} <ul> {% for FWinst in FW_list %} {% if FWinst.is_approved %} <li class="{% if FWinst.is_approved %}text-danger{% endif %}">--> <a href="{% url 'FW-detail' FWinst.pk %}">{{FWinst.ODM_name}}</a> ({{ FWinst.project_name }}) </li> {% endif %} {% endfor %} </ul> {% else %} <p>Nothing.</p> {% endif %} {% endblock %} the image of FWinstance_list_applied_user.html, when I click the link CSR, nothing happened -
testing detail actions in viewsets
I wrote a viewset with a set authentication, permissions and serializers, and would like now to unit test it. The problem is that when executing UserViewSet.as_view(actions={'get': 'retrieve'}) from my test, the viewset dispatch method doesn't set self.detail = True. class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer lookup_field = 'pk' authentication_classes = (FirebaseAuthentication,) permission_classes = (IsFirebaseVerified, IsAuthenticatedOrReadOnly) queryset = User.objects.all() def get_serializer_class(self): ''' if a user queries his own details, or signs up, return his private info ''' # BUG: self.detail is undefined if (self.detail and self.request.user.pk == self.kwargs.get('pk'))\ or self.action == 'create': return PrivateUserSerializer return UserSerializer Related test: def generate_fake_user_data(pk, name): return { 'pk': pk, 'email': '{}@example.com'.format(name.lower()), 'password': 'password{}'.format(name), } class UserViewSetTestCase(TestCase): @classmethod def setUpClass(cls): cls.users = MockSet( User(**generate_fake_user_data(1, 'A')), User(**generate_fake_user_data(2, 'B')), model=User, ) cls.factory = APIRequestFactory() UserViewSet.queryset = cls.users @classmethod def tearDownClass(cls): UserViewSet.queryset = User.objects.all def test_authed_user_retrieves_himself(self): request = self.factory.get('/api/users/1/') force_authenticate(request, user=self.users.first()) retrieve_view = UserViewSet.as_view(actions={'get': 'retrieve'}) response = retrieve_view(request, pk=1) # BUG: response.data has been returned by UserSerializer self.assertDictContainsSubset({ 'pk': 1, 'full_name': 'John A', 'email': 'a@example.com', }, response.data) self.assertFalse('password' in response.data) What would be the proper way to call my view from my test with self.detail being set to True ? -
How do I redirect unauthenticated visitor on my extended Django Admin page?
I've added a new path admin/testing/ on project's urls.py like this ... path('admin/', admin.site.urls), path('admin/testing/', TemplateView.as_view(template_name='admin/testing/testing.html')), ... and also testing.html on my_app/templates/admin/testing/testing.html, but I am able visit admin/testing/ without login first. On testing.html I've a got a form there, only when I submit the form then it will prompt an alert to ask me to enter my username and password. {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}" />{% endblock %} {% block coltype %}colMS{% endblock %} {% block bodyclass %}{{ block.super }} dashboard{% endblock %} {% block breadcrumbs %}{% endblock %} {% block content %} <div id="content-main"> <div id="testing-root"></div> <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script type="text/babel"> class AdminTesting extends React.Component { ... render() { const { state } = this; return ( <div> <h2>Transform Users Play Count into Ratings</h2> <form> Weight:<br/> <input type="number" step={0.1} name="transformWeight" value={state.transformWeight} onChange={this.handleChangeFraction} /><br/> <input style={styles.btn} type="submit" value="Submit" onClick={this.handleRatingTransformation} /> { state.transformLoading && 'Please wait ...' } </form> ... </div> ) } } ... ReactDOM.render( <AdminTesting/>, document.getElementById('testing-root'), ); </script> </div> {% endblock %} -
Django Many2Many Annotation
I have two Django tables: A and B. There's a many2many relationship between them, written in table A. The problem I have is that when I serve this as an API and I present the objects as A.objects.all().values(), the values of B don't showup. I want to annotate Django table A with the ids of the many2many relationship, so that I can pull them when I do A.objects.all().values(), to get A.B_ids=['134','141','1414']. -
Django with Ldap installation build failed
I'm new to Python Django and I'm building my Django application on Windows 7. My requirement is to integrate LDAP with Django. So I followed the below URL to install LDAP Installation- Django-LDAP When I try to install LDAP followed by pip install django-auth-ldap Then I'm getting Collecting django-auth-ldap Using cached https://files.pythonhosted.org/packages/c1/c4/e1586a835b5bf76d4d914f1622020ae9ab9d9be7149e216e19c8428670d1/d jango_auth_ldap-1.7.0-py2.py3-none-any.whl Requirement already satisfied: Django>=1.11 in c:\users\ccduce\appdata\local\continuum\miniconda3\lib\site-packages (from d jango-auth-ldap) (2.0.6) Collecting python-ldap>=3.1 (from django-auth-ldap) Using cached https://files.pythonhosted.org/packages/7f/1c/28d721dff2fcd2fef9d55b40df63a00be26ec8a11e8c6fc612ae642f9cfd/p ython-ldap-3.1.0.tar.gz Requirement already satisfied: pytz in c:\users\ccduce\appdata\local\continuum\miniconda3\lib\site-packages (from Django>=1 .11->django-auth-ldap) (2018.4) Requirement already satisfied: pyasn1>=0.3.7 in c:\users\ccduce\appdata\local\continuum\miniconda3\lib\site-packages (from python-ldap>=3.1->django-auth-ldap) (0.4.4) Requirement already satisfied: pyasn1_modules>=0.1.5 in c:\users\ccduce\appdata\local\continuum\miniconda3\lib\site-package s (from python-ldap>=3.1->django-auth-ldap) (0.2.2) Building wheels for collected packages: python-ldap Running setup.py bdist_wheel for python-ldap ... error Complete output from command c:\users\ccduce\appdata\local\continuum\miniconda3\python.exe -u -c "import setuptools, toke nize;__file__='C:\\Users\\ccduce\\AppData\\Local\\Temp\\pip-install-c5a5rvyv\\python-ldap\\setup.py';f=getattr(tokenize, 'o pen', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C :\Users\ccduce\AppData\Local\Temp\pip-wheel-6ztc_mq2 --python-tag cp36: polls\views.py17:1 LFUTF-8Python0 files running build_ext building '_ldap' extension error: [WinError 3] The system cannot find the path specified: 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC \\PlatformSDK\\lib' ---------------------------------------- Failed building wheel for python-ldap Running setup.py clean for python-ldap Failed to build python-ldap Installing collected packages: python-ldap, django-auth-ldap Running setup.py install for python-ldap ... error Complete output from command c:\users\ccduce\appdata\local\continuum\miniconda3\python.exe -u -c "import setuptools, to kenize;__file__='C:\\Users\\ccduce\\AppData\\Local\\Temp\\pip-install-c5a5rvyv\\python-ldap\\setup.py';f=getattr(tokenize, 'open', … -
Django redirects to /accounts/profile
I have written some middleware that restricts access to all URLs except the exempted ones. A user can access all the URLs only if they are logged in, if not logged-in, a user can only access exempted URLs. The problem comes when the user is logged-in and then tries to access one of the exempted URLs, that is when the redirect occurs (i.e. redirected to /accounts/profile). How can I solve this problem? -
Django Rest Framework: How to show serialized value in django template?
I am trying to show the serialized data in the Django template. I am using Django Rest framework. Using Ajax I have just tried to show the serialized data in a textarea in the html template view. In view.py, at first, I tried to make a dictionary from a list. And then send it to the serializer.py to make it JSON data. After doing this I just send that serialized data. And from the template, I am using ajax to get this data and set this value in a textarea which is get by ID identifier. But it does not show the value in the textarea. In the textarea, it just prints "[object Object]". So, how do I show the serialized data in the textarea? Here is my view.py: @csrf_exempt def result(request): text = request.POST['test'] triples = getTriples(text) keys = ['sub','predi','obj'] demo_data = dict(zip(keys,triples[0])) serializer = SentenceListSerializer(data=demo_data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False) Ajax code: $.ajax({ url: "{%url 'result' %}", method: 'POST', dataType: 'json', async: true, headers: { 'X-CSRFToken': $("input[name='csrfmiddlewaretoken']").val() }, data: {'test': info}, success: function(response_data){ $('#textareashow').val(response_data); } }); -
Django: Dependent Dropdown List
I want to implement Dependent Dropdown List in my project. Here are the models: class ObjectName(models.Model): objectName=models.CharField(max_length=100) objFullForm=models.CharField(max_length=100, default='') def __str__(self): return self.objectName class ActionObject(models.Model): objectName=models.ForeignKey(ObjectName,on_delete=models.CASCADE) action=models.CharField(max_length=100) def __str__(self): return self.action When the user selects an object in the ActionObject template, the Action should automatically list the related fields. I tried using Django-smartselects but it didn't work. -
Django : request.POST error "__init__() takes 1 positional argument but 2 were given"
I have a simple form in my Django project: forms.py class DamageListCriteria(forms.Form): fromdate = forms.CharField(widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'})) todate = forms.CharField(widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'})) class Meta: fields = ['fromdate','todate'] views.py class DamageListCriteria(TemplateView): template_name = "damage/damagelist_criteria.html" def get(self, request): form = DamageListCriteria() general = General.objects.get(pk=1) args = { 'form': form, 'general': general } return render(request, self.template_name, args) def post(self, request): general = General.objects.get(pk=1) form = DamageListCriteria(request.POST) args = { 'form': form, 'general': general } return render(request, self.template_name, args) urls.py url(r'damage/list/criteria/$', views.DamageListCriteria.as_view(), name="damage-list-criteria"), when I try to post I am getting this error : '__init__() takes 1 positional argument but 2 were given' the error is on the form = DamageListCriteria(request.POST) line of code. Thanks in advance for your time -
Jquery AJAX relative paths concatenated with current url
I am having the following AJAX request to some location mentioned in the URL field. when I try to send this request, It concatenates the current URL (from browser) and append this AJAX URL with it and my PUT request fails all the time. jQuery.ajax({ type: 'PUT', url: 'qres/pfolio/v1/'+portfolio_id+'/', data: put_data, success: function(result) { console.log(result); }, }); if the current page url from browser it "http://localhost:8000/portfolio/2/" then the ajax call goes to "http://localhost:8000/portfolio/2/qres/pfolio/v1/2/" How can I correct the relative url so that It goes to "http://localhost:8000/qres/pfolio/v1/2/" -
Python-Django: coercing to Unicode: need string or buffer, InMemoryUploadedFile found
I am trying to upload a file in a page and fetch the file and open it in Django But I get "coercing to Unicode: need string or buffer, InMemoryUploadedFile found" def model_form_upload(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): form.save() file = request.FILES['file'] open(file, 'rb+') return render(request, 'virus/home.html') else: form = FileForm() return render(request, 'virus/upload.html', { 'form': form }) I have already tried a lot to figure it out. But still can't Any helps will be appreciated. -
How Do I See Which User/Group is Running My Django Application?
I am currently developing my Django loggers and I have a question when it comes to writing to a new file that has not been created yet. I know Django is supposed to create the new file if it is not already there (the log file) and then write to it there. My issue is that, whichever user is running the Django application (presumably the one I launched it under, or even www-data?) does not have access to that directory. How I got it to finally do as I needed, is I opened up the directory to be writable by all. This is, in my opinion very unsafe and definitely not wanted. I tried this to make sure my loggers were properly setup and it works as desired when I make this change. I have since closed off those permissions and now I am back to square 1 until I find out a solution. Main Question How do I find out which user is running Django, or at least whatever it is that is trying to create the file, in order to add them to a group that has write access to that directory? -
Django Models: Multiplication of two fields
I want to multiply two fields from the model and display it in a template. I have two models: class Priority(models.Model): priorityName=models.CharField(max_length=100) priorityScore=models.IntegerField() def __str__(self): return str(self.priorityScore) class ImpactMatrix(models.Model): objectName=models.ForeignKey(ObjectName,on_delete=models.CASCADE) actionName=models.ForeignKey(ActionObject,on_delete=models.CASCADE) priority=models.ForeignKey(Priority,on_delete=models.CASCADE,related_name='priority') functional=models.ForeignKey(Priority,on_delete=models.CASCADE,related_name='functional') supervision=models.ForeignKey(Priority,on_delete=models.CASCADE,related_name='supervision') approval=models.ForeignKey(Priority,on_delete=models.CASCADE,related_name='approval') I want to multiply the priorityScore in ImpactMatrix.priority * ImpactMatrix.functional How do I do this? -
Different errors coming from different host values for mysql config in docker project
I'm contributing to a new project, but getting info about the setup/build is difficult. I can get through these steps in the build process: $ docker-machine create -d virtualbox dev; $ eval $(docker-machine env dev) $ docker-compose build $ docker-compose up -d The next command fails: $ docker-compose run web /usr/local/bin/python manage.py migrate ...with this error: (2005, "Unknown MySQL server host 'mysql' (0)") When I change the mysql HOST from mysql to localhost, I get a new error: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") I've read about each error, but the proposed solutions aren't relevant to my code (besides the suggestion of setting the HOST to localhost). Which host value is correct and what should be done about the respective error? I'm not actually sure if mysql is running, where it should be running, and how to check its status. -
Django-mptt - sorting post by categories
I am new in django. I am trying to create a category system on my site. I used Django-mptt. I want to have a view that sorts posts by category. tree: Category -Subcategory -Subcategory Category -Subcategory -Subcategory models.py class Post(models.Model): title = models.CharField(max_length=250) category = TreeForeignKey('Category', on_delete=models.CASCADE, related_name='post') class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_absolute_url(self): return reverse('list_of_post_by_category', args=[self.slug]) def __str__(self): return self.name def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs views.py def list_of_post_by_category(request, slug): categories = Category.objects.all() category=get_object_or_404(Category, slug = slug) posts = Post.objects.filter(category=category) return render(request, "account/list_of_post_by_category.html", {'categories': categories, 'posts': posts, 'category': category}) urls.py url(r'^category/(?P<slug>[-\w]+)/$', views.list_of_post_by_category, name= 'list_of_post_by_category') list_of_post_by_category.html {% for post in posts %} <div class="single_post"> <a href="{{ post.get_absolute_url }}">{{ post.title }}</a> <br/> <br/> <div> {{ post.publish }} {% for parent in post.category.get_ancestors %} {{ parent.name }} / {% endfor %} {{ post.category }} </div> </div> {% endfor %} My problem is that the site does not show any posts. I think … -
Django Memcached Authentication Tokens // is_authenticated attribute
I was looking into caching (memcached or redis) user tokens so that we can save a round-trip to DB on every request of our django-rest-framework-api. Had a few questions Is this entirely irresponsible? What method would we override/extend to make this possible? I can't seem to find a single source: we use both the rest_framework IsAuthenticated, and the request.user.is_authenticated across our endpoints If it were safe, what length cache would you recommend? Any advice? Where should I start? -
MailgunAPIError<Response [400]> with django-registration-redux
I'm trying to send registration emails by django-registration-redux, but got this response code: MailgunAPIError Response [400]. The code means 'Bad Request - Often missing a required parameter' But i can send an email manually on my site, it's functional. Am I missed some required parameter between registration-redux and mailgun? This is my setting: INSTALLED_APPS = (..., 'registration' , ) ACCOUNT_ACTIVATION_DAYS = 7 EMAIL_BACKEND = 'django_mailgun.MailgunBackend' MAILGUN_ACCESS_KEY = 'xxxx' MAILGUN_SERVER_NAME = 'xxxx' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.mailgun.org' EMAIL_HOST_USER='postmaster@xxxx' EMAIL_HOST_PASSWORD= 'xxxx' EMAIL_PORT = 587 And this is my urls setting path('accounts/', include('registration.backends.default.urls') -
Translating Django URLS.py for WinSCP
I'm using WinSCP to deploy a Django project to Digital Ocean. I have Django 2.0.3 but WinSCP only can upgrade up to 1.8.7. I'm getting errors when trying to configure the urls.py in WinSCP. I'm unfamiliar with the older versions of Django, so any advice on how to translate my urls.py (and project in general) to fit their version would be helpful. My urls.py : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] -
Django Query - Select Where
I have a Client, Users and ClientUsersAssignment table. Clients are assigned to one more more users. I need to retrieve the list of clients the given user has access to. How do I construct my filter? I have included the SQL equivalent in the snippet below. Client.objects.filter ( # SQL Equivalent Statement WHERE request.user.id IN (SELECT user FROM ClientStaffAssignment WHERE clientid = client.id) ) And the django models for completeness: class User(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=50, blank=True, null=True) class Client(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True, null=True) class ClientStaffAssignment(models.Model): id = models.AutoField(primary_key=True) client = models.IntegerField(blank=True, null=True) user = models.ForeignKey (User, blank=True, null=True) -
NoReverseMatch in Django:Reverse for ....l' with arguments '('',)' not found. 1 pattern(s) tried:
Django 2.0 python 3.7 win7 urls.py urlpatterns += [ url(r'^myFWs/', views.LoanedFWsByUserListView.as_view(), name='my- applied'), url(r'^myFWs/(?P<pk>[0-9]+)$', views.FWDetailView.as_view(), name='FW-detail'), ] view.py `from .models import FW class LoanedFWsByUserListView(LoginRequiredMixin,generic.ListView): model = FW paginate_by = 10 template_name = 'catalog/FWinstance_list_applied_user.html' def get(self, request): form = FWForm() FW_list = FW.objects.all() return render_to_response(self.template_name, locals()) FWinstance_list_applied_user.html: ` {% block content %} <h1>Applied FWs</h1> <p>FW_list:</p>{{FW_list}} {% if FW_list %} <ul> {% for FWinst in FW_list %} <li class="{% if FWinst.is_approved %}text-danger{% endif %}">--> <a href="{% url 'FW-detail' FWinst.FW.pk %}">{{FWinst.ODM_name}}</a> ({{ FWinst.project_name }}) </li> {% endfor %} </ul> {% else %} <p>Nothing.</p> {% endif %} {% endblock %}` ` the mistake is : NoReverseMatch at /catalog/myFWs/ Reverse for 'FW-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/myFWs/(?P[0-9]+)$'] -
Multiple FusionCharts on Same page with Django
I am trying to build a dashboard type site with multiple charts. I am using Django with FusionCharts and a Postregsql database backend. I am able to get one chart to render, but I can't get a second one to appear at all. I think it is probably something in my views.py with how I am creating the functions. Any help is much appreciated. Code is as follows: views.py from django.shortcuts import render from django.http import HttpResponse # Include the `fusioncharts.py` file that contains functions to embed the charts. from .fusioncharts import FusionCharts from .models import * # The `chart` function is defined to load data from a `Country` Model. # This data will be converted to JSON and the chart will be rendered. def chart(request): # Chart data is passed to the `dataSource` parameter, as dict, in the form of key-value pairs. dataSource = {} dataSource['chart'] = { "caption": "Final Sale Price by Customer", "showValues": "0", "theme": "fint" } dataSource['data'] = [] for key in Customer.objects.all(): data = {} data['label'] = key.customername data['value'] = key.Final_Price dataSource['data'].append(data) column2D = FusionCharts("column2D", "ex1", "600", "350", "chart-1", "json", dataSource) return render(request, 'dashboard.html', {'output': column2D.render()}) def chart2(request): # Chart data is passed to the … -
ManyToMany as Inline
When trying to use a ManyToMany relation as an Inline in a ModelAdmin, cause the error admin.E105 at the bottom, but under normal circunstances, without inline, it works fine. Here is the code: models.py class Reference(models.Model): url = models.UrlField() ... class BaseModel(models.Model): ... references = models.ManyToManyField( Reference, related_name="references_%(app_label)s_%(class)s_related", ) class Meta: abstract=True class Case(BaseModel) ... name = models.CharField(max_length=255) ... admin.py class InlineReference(admin.TabularInline): model = ContentBaseModel.references.through class CaseAdmin(admin.ModelAdmin): ... inlines = [InlineReference, ] exclude = ['references', ] ... SystemCheckError: System check identified some issues: ERRORS: <class 'admin.CaseAdmin'>: (admin.E105) 'admin.InlineReference' must have a 'model' attribute. I'm trying to follow the docs from here: Any help is appreciated. Thanks