Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to build a Django queryset based on more models
So what I say might seem complicated, but I think the answer is easy. I just can't figure it out. I have a form for a Lecture model, which a logged in teacher can use to post a lecture for his specific courses only. Thing is that in my database I have a TeacherData model which contains a teacher_ID field used for verification, so a teacher cannot create his account on the other Teacher model, if teacher_ID entered doesn't match. But when a course is created in database, the teacher used is the one from TeacherData. So to create my query I have to filter the courses based on TeacherData and then using teacher_ID, to link to Teacher model. I just don't know how to build this queryset but I replicated the wanted behaviour in the template: {% if user.is_authenticated and user.is_teacher %} <ul> {% for data in teacher_data %} {% if data.teacher_ID == user.teacher.teacher_ID %} {% for course in courses %} {% if course.teacher1 == data or course.teacher2 == data %} <li> <a href="{% url 'courses:courses' slug=course.slug %}">{{ course.name }}</a> </li> {% endif %} {% endfor %} {% endif %} {% endfor %} </ul> {% endif %} class Teacher(models.Model): … -
No connection with dockerized nginx gunicorn
I've created simple example for dockerized django with nginx and gunicorn. But for some reason connection doesn't go through nginx. Here is nginx.conf contents worker_processes 1; error_log /var/log/nginx/error.log info; events { worker_connections 1024; } http { gzip on; gzip_http_version 1.1; gzip_comp_level 2; include /etc/nginx/mime.types; default_type application/octet-stream; server { listen 80; server_name www.example.dj example.dj; location = /favicon.ico { alias /app/static_root/favicon.ico; } location /static/ { alias /app/static_root/; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/app/example.sock; } } } docker-compose.yml file version: '3' services: web: build: . hostname: web command: bash -c "python manage.py migrate && gunicorn example.wsgi:application --workers 3 --bind unix:/app/example.sock" volumes: - ./src:/app expose: - "8000" nginx: image: nginx:latest ports: - "80:8000" volumes: - ./src:/app - ./config/nginx/nginx.conf:/etc/nginx/nginx.conf depends_on: - web In /etc/hosts I have 127.0.0.1 www.example.dj example.dj So when I run docker-compose up I expect to see django start page by http://example.dj url, but there is no connection. Can you guys help me with it? Code available on the github -
How to multiply a floating point number and a decimal in Django?
I am using django 2.0 and Python 3.6.4 I have a field in my model called total which is a decimal field. total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) I want to calculate the value after multiplying it with 1.15 in a function. def calculate_tax(self): tax_total = instance.total * Decimal(1.15) It's giving me errors: unsupported operand type(s) for *: 'float' and 'Decimal' -
How to update only the queried objects in django
I have a table ActivityLog to which new data is added in every second. I am querying this table every 5 seconds using an Api in the following way. logs = ActivityLog.objects.prefetch_related('activity').filter(login=login_obj,read_status=0) Now let's say when I queried this table at time 13:20:05 I've got 5 objects in logs and after my querying 5 more rows were added to the table at 13:20:06. When I try to update only the queried logsdataset using logs.update(read_status=1) it also updates the newly added data in the table. That is instead of updating 5 objects it updates 10 objects. How can I update only the 5 objects that I've queried without looping through it. -
Csv File Not Found in Django
I am probably missing something obvious but my python code does not recognise my csv file although it is included in my package. As a result, I am getting a FileNotFoundException. Here is my error: from multiplication import views File "/Users/NikolasPapastavrou/firstProject/multiplication/views.py", line 15, in <module> with open('data.csv','r') as csv_file: FileNotFoundError: [Errno 2] No such file or directory: 'data.csv' Here is a picture of my setup, including the file in the package: https://i.stack.imgur.com/l1pW7.png -
Staticfile issue when trying to deploy django
I am trying to deploy Django following this tutorial but am getting an error. When the tutorial says to run python manage.py collectstatic, instead of collectstatic running without further prompt as suggested, I get the following: /home/elections/venv/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes I entered Yes and got the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/elections/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/elections/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/elections/venv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/elections/venv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/elections/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/home/elections/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect handler(path, prefixed_path, storage) File "/home/elections/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 354, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/elections/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 260, in delete_file if self.storage.exists(prefixed_path): File "/home/elections/venv/lib/python3.6/site-packages/django/core/files/storage.py", line 392, in exists return … -
Django ReST Framework - Extended User model not accepting "null=true"
I have checked a lot of similar questions but no one has encountered such an issue in django shell : I am using Django 2 and DRF 3.7.7 with Python 3.6 and PostgreSQL 10.1 on Ubuntu 16.04 LTS. I am writing a booking application and trying to extend Django user model with OneToOneField (Using the guide here without using Signals' methods). I have had some experiences coding in Python 2.7 for some time, but this is my first experience with Django. So here is my models.py : from django.db import models from django.contrib.auth.models import User # Create your models here. SPORTS_CHOICES = ( ('Mountain', 'Mountain climbing'), ('Offroad', 'Offroad Driving'), ('Rafting', 'Rafting'), ('Cycling', 'Cycling'), ('Ski', 'Skiing'), ) class ListField(models.TextField): "ListField stores List of element" SPLIT_CHAR= ';' def __init__(self, *args, list_choices=None, **kwargs): super(ListField, self).__init__(*args, **kwargs) if list_choices is None: list_choices = [] self.list_choices = list_choices def get_prep_value(self, value): if value is None or value == "": return None res = self.SPLIT_CHAR.join(value) return res def value_to_string(self, obj): value = self._get_val_from_obj(obj) return self.get_prep_value(value) class Profile(models.Model): "The Profile of a user with details are stored in this model." user = models.OneToOneField(User, on_delete=models.CASCADE, max_length=11) first_name = models.TextField(max_length=50,null=True) last_name = models.TextField(max_length=100,null=True) # The default username is phone … -
Recommendation for full text search option for Django web
I have a website with monthly pageviews around half a million. I am planning to implement a search functionality on site. I am stuck with different options available. I want to go with a package which is easy to use and can search from multiple models (basically its a CMS website with multiple Models.) What you think of django-watson? What about django inbuilt postgres full text search? Does it support searching from multiple models and ranking contents from multiple models? -
The 'order_by' method not working on a foreign key query
I can't figure out how to get this 'order_by' to work. reviews = product.review_set.all().order_by('-created_at') -
Django, compare list of dates in form field to check if exist for user
I have this problem, I have a system of reservations that needs to limit reservations made in Friday, for the user, to be only one per month, Friday is the last day the users can make a reservation. I made a range of dates that correspond to Friday in the month using a library called pandas, this gets me a list of dates. import calendar import pandas as pd from datetime import date fecha = date.today() _, dias = calendar.monthrange(fecha.year, fecha.month) primer_dia_mes = date(fecha.year, fecha.month, 1) ultimo_dia_mes = date(fecha.year, fecha.month, dias) dias_viernes = pd.date_range(start=primer_dia_mes, end=ultimo_dia_mes, freq='W-FRI').strftime('%Y-%m-%d').tolist() Ok, now Im trying to make a way to validate this list of dates with the date that the user put in the date field in the form. def post(self, request): form = ReservacionForm(request.POST) reservaciones = Reservaciones.objects.exclude(usuario=request.user) reservaciones_usuario = Reservaciones.objects.filter(usuario=request.user) reservaciones_fechas = Reservaciones.objects.filter(usuario=request.user, envio=timezone.localdate()).count() fecha = date.today() _, dias = calendar.monthrange(fecha.year, fecha.month) primer_dia_mes = date(fecha.year, fecha.month, 1) ultimo_dia_mes = date(fecha.year, fecha.month, dias) dias_viernes = pd.date_range(start=primer_dia_mes, end=ultimo_dia_mes, freq='W-FRI').strftime('%Y-%m-%d').tolist() for f, u in zip(dias_viernes, reservaciones_usuario): if str(u.fechas) == str(f): fin_semana_mes = True else: fin_semana_mes = False if form.is_valid() and fin_semana_mes == False: if reservaciones_fechas < MAX_RESERVATION_POST: nucleo = form.cleaned_data['nucleo'] cabaña = form.cleaned_data['cabaña'] fechas = form.cleaned_data['fechas'] post … -
Explanation of Django Table Relations and How they are Being Called
I'm fairly new to Django and am currently trying to go through and modify a preexisting website. I'm trying to understand the syntax involved with creating a chart based on certain parameters. Currently the site takes account types as an argument and spits out a plot of account values vs. years. As shown in the first picture: Picture of Plot The part of the code I'm confused about is here: tag_ids = [56, 123, 15, 21, 82] if categories_1: tag_ids = categories_1.split(',') tags = [] funding_announced_min = minyear+'-01-01' funding_announced_max = maxyear+'-12-31' business_list = [] for d in tag_ids: tag1 = Tag_objs.objects.get(pk=int(d)) tags.append(tag1) business_1 = tag1.buisiness.filter( company__founded_date__gte=funding_announced_min, company__founded_date__lte=funding_announced_max, entity_type=0, ) business_list.append(business1) tag is a table of account types, and my confusion comes from the business_1 = tag1.business.filter section. What exactly is this doing? I have a model called biz that looks like this: class biz(Ent): founded_date = models.DateField(blank=True, null=True) employee_amount = models.IntegerField('Number of Employees',blank=True, null=True) employee_amount_range = models.CharField(max_length=64, blank=True, null=True) biz_status = models.CharField(choices=BIZ_STATUS_CHOICES, max_length=32, default='operating', blank=True, null=True) zipcode = models.CharField(max_length=64, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) funding_rounds = models.IntegerField(default=0, blank=True, null=True) funding_total_usd = models.BigIntegerField(default=0, blank=True, null=True) first_funding_on = models.DateField(blank=True, null=True) last_funding_on = models.DateField(blank=True, null=True) closed_on = models.DateField(blank=True, null=True) employee_count_min = … -
django-import-export form <input> not rendering in custom admin template w/ grappelli
after implementing django-import-export on a project using django-grappelli for admin UI, I've discovered there are some CSS incompatibilities between the two libs: https://github.com/sehmaschine/django-grappelli/issues/435 to address this, I created custom admin template overwrites so import-export uses grappelli's CSS: /templates/admin/import_export/base.html {% extends "admin/base_site.html" %} {% load i18n admin_static admin_modify %} {% load admin_urls %} {% block bodyclass %}{{ opts.app_label }}-{{ opts.object_name.lower }} change-form{% endblock %} {% if not is_popup %} {% block breadcrumbs %} <ul> <li><a href="{% url 'admin:index' %}">{% trans 'Home' %}</a></li> <li><a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_label|capfirst|escape }}</a></li> <li><a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst }}</a></li> <li> {% block breadcrumbs_last %}{% endblock %}</li> </ul> {% endblock %} {% endif %} /templates/admin/import_export/change_list.html {% extends "admin/change_list.html" %} {% load i18n grp_tags %} {# Original template renders object-tools only when has_add_permission is True. #} {# This hack allows sub templates to add to object-tools #} {% block object-tools %} <ul class="grp-object-tools"> {% block object-tools-items %} {% if has_add_permission %} {{ block.super }} {% endif %} {% endblock %} </ul> {% endblock %} /templates/admin/import_export/import.html {% extends "admin/import_export/base.html" %} {% load i18n grp_tags %} {% load admin_urls %} {% load import_export_tags %} {% block breadcrumbs_last %} {% trans "Import" %} {% endblock %} {% block … -
How to fix Python MySQL connection issue, Python 2.7, MySQL 5.7
I'm working with an Ubuntu (Linode) 16.04 LTS / nginx / uwsgi / Python-2.7 / Django / MySQL 5.7 application. A little more than a month ago the box was dist upgraded from 14.04 LTS, and at that time or soon after that MySQL was upgraded from 5.5 to 5.7. We had to recreate the Python virtual environment, and then things worked fine. Up until today when Linode Fremont experienced issues, and the box was restarted. Since that restart we are experiencing undeterministic MySQL restarts. One suspicion is a possible file system corruption in case the restart was preceded by a "pull the plug out" type power down (the report contains the keyword power failure). I restarted again the box forcing fsck, and I still won't rule that out completely, but I rather seek for software issues. The MySQL logs don't contain any suspicious. The uwsgi logs however show: ...The work of process 27651 is done. Seeya! worker 1 killed successfully (pid: 27651) Respawned uWSGI worker 1 (new pid: 27686) Fri Feb 23 18:33:38 2018 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) !!! Traceback (most recent call last): File "/opt/webapps/.virtualenvs/company/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__ self.load_middleware() File … -
Django error : :SyntaxError:Invalidsyntax
i am new in django . i learn from youtub django webdevlopment with python.while runserver i found this error: File "C:\Users\Dell\AppData\Local\Programs\Python\Python36-32\new\personal\urls.py", line 1, in <module> from . import views File "C:\Users\Dell\AppData\Local\Programs\Python\Python36-32\new\personal\views.py", line 6 ` ^ and in new/urls.py File "C:\Users\Dell\AppData\Local\Programs\Python\Python36-32\new\new\urls.py", line 21, in <module> url(r'^personal/',include('personal.urls')), File "C:\Users\Dell\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Users\Dell\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) my personal/urls.py is: from . import views from django.conf.urls import * urlpatterns = [ url('personal/',views.index,name='index'), ] and personal/view.py is: from django.shortcuts import render def index(request): return render(request,'personl/home.html') # Create your views here. ` new/urls.py is: " ""new URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.conf.urls import * urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^personal/',include('personal.urls')), url(r'^block/ ',include('block.urls')), ] Thanks in advance -
Can a Django project backend server run in two environments?
Can a Django project backend server run in two environments? I have a Django-Rest-Framework project( using Python write the project ) as the backend to provide APIs, and now I want to add a application to as a app in my backend. The application is written using node.js. Can I use two environments to run the backend project? -
How can I combine CreateView and Bootstrap modal inside current url
Let me crearify the question: I want to create a post through a Bootstrap modal which is hosted in my blog home where there are already a ListView of all posts rendered. In my head, to create a new post, I need another template, set up its url and then set up the view. So I started searching for ways which led me to a certain point with no clues of what I'm doing and the form is not being rendered in the modal, and when I click on submit button of the form, the page reloads, but interestingly the url of my blog home keeps the same, and the only thing that change is the page which turn into a blank white page, also, the logs of the server shows me: Method Not Allowed (POST): /blog/ [23/Feb/2018 23:24:09] "POST /blog/ HTTP/1.1" 405 0 Bellow is my blog app url partterns setup: urlpatterns = [ path('blog/', BlogHomeView.as_view(), name='blog-home'), path('blog/create_post/', BlogCreatePostView.as_view(), name='create- post'), ] Now down is the view for the blog home, which render a ListView, and a view for creating a post, CreateView: class BlogHomeView(ListView): model = BlogPostsModel template_name = 'blog/blog.html' class BlogCreatePostView(CreateView): template_name = 'blog/create.html' form_class = CreatePostForm … -
Django: request user's name in the file settings.py
I am implementing a function in the file settings.py, and I need to get the user name in the same function, something like this: def function(request, input): username = str( request.user ) return input + username But the I get the error: NameError: global name 'request' is not defined Any idea how I can solve this? Thank you very much for your help ! -
Uploading Files in Django - How to avoid the increase of files in the upload directory
I've been working on uploading a file on Django. I have the following code to run things. def handle_uploaded_file(file, filename): if not os.path.exists('upload/'): os.mkdir('upload/') with open('upload/' + filename, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) def upload_csv(request): # Get the context from the request. context = RequestContext(request) if request.is_ajax(): if "POST" == request.method: csv_file = request.FILES['file'] my_df = pd.read_csv(csv_file, header=0) handle_uploaded_file(csv_file, str(csv_file)) ............................. ............................. As you can see above, I have been uploading files to the upload directory. However, my concern is that this type of method might not be that much efficient because each file is kept and stored in that folder. What if hundreds or thousands of files are uploaded each week? See this: What would be the other way to efficiently and effectively upload files? -
Attribute Error while creating new User object in django
This is my customized User Object in django. class User(AbstractBaseUser, PermissionsMixin): mobile = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=255, null=True) username = models.CharField(max_length=255, null=True) full_name = models.CharField(max_length=255, blank=True, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True) USERNAME_FIELD = 'mobile' REQUIRED_FIELDS = [] objects = UserManager() And this is the UserManager, class UserManager(BaseUserManager): def create_user(self, mobile, email=None, username=None, full_name=None, password=None, is_staff=False, is_superuser=False): if not mobile: raise ValueError("Can't create User without a mobile number!") if not password: raise ValueError("Can't create User without a password!") user = self.model( mobile=mobile, email=self.normalize_email(email), username=username, full_name=full_name, is_staff=is_staff, is_superuser=is_superuser, ) user.set_password(password) user.save(self._db) return user This is my UserSerializer Class class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) id = serializers.IntegerField(read_only=True) class Meta: model = models.User fields = ( 'id', 'mobile', 'email', 'username', 'full_name', 'password', ) And this is the view where I'm trying to register a User. class RegisterView(views.APIView): def post(self, request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): user = UserManager().create_user(mobile=serialized.mobile, email=serialized.email, username=serialized.email, full_name=serialized.full_name, password=serialized.password) if user: return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized.errors, status=status.HTTP_400_BAD_REQUEST) I end up getting the following error message, AttributeError at /api/v1/bouncer/register/ 'UserSerializer' object has no attribute 'mobile' But of course I've a mobile attribute. What am I doing wrong here? -
How to modify Django's DateTimeInput widget to select times at 15-minute increments instead of 30?
I have a form with a default DateTimeField which includes a drop-down menu for the time of day in 30-minute increments: I'd like to change this so that times are selectable at 15-minute increments instead of 30-minute ones. Looking into Django's source code (https://github.com/django/django/blob/master/django/forms/widgets.py) for the DateTimeInput widget (which is the default widget for DateTimeField), it is not immediately clear to me how I would customize it to adjust the interval spacing: class DateTimeInput(DateTimeBaseInput): format_key = 'DATETIME_INPUT_FORMATS' template_name = 'django/forms/widgets/datetime.html' Any ideas how I might go about this customization? Or should I choose a different, readily available widget? -
How to make log.django delete/clear after exiting?
I'm running my Django website on Ubuntu 16.04 on a remote Digital Ocean server. Every time there is an error, it is appended to my log.django file. So it's now over 25,000 lines and every time I want to see an error I have to scroll to the bottom of the file. Is there a way I can clear the contents of the file every time I exit it? -
Django formset error
I'm trying to setup line items as a formset in django ( charges) to add to a work-order. I've tried adding the field directly into modelformset_factory in ChargesCreateView, but still nothing ( even though i already have fields set in my forms.py ). the error is ImproperlyConfigured at /workorders/charges/create/1219/ Using ModelFormMixin (base class of ChargesCreateView) without the 'fields' attribute is prohibited. view.py class ChargesCreateView(generic.CreateView): # form_class = LineitemForm LineitemFormSet = modelformset_factory(Lineitem,form=LineitemForm) formset = LineitemFormSet() template_name = 'workorders/form_create_charges.html' success_url = '/workorders/' def get_initial(self): return { 'workorder': self.kwargs.get('pk'),} def get_queryset(self): workorders = Workorder.objects.all().values() return workorders model.py class Lineitem(models.Model): workorder = models.ForeignKey('Workorder', null=False, on_delete=models.CASCADE) sku = models.CharField(max_length=20) description = models.CharField(max_length=100) qty = models.IntegerField(null=True) unit_price = models.IntegerField(null=True) discount = models.IntegerField(null=True) amount = models.IntegerField(null=True) def __str__(self): return self.sku forms.py class LineitemForm(forms.ModelForm): class Meta: model = Lineitem fields = [ 'workorder', 'sku' ] widgets = { 'workorder': forms.HiddenInput(), } form_create_charges.html <form method="post" novalidate> {% csrf_token %} <table border="0"> {{ formset.management_form }} {{formset}} </table> <button type="submit" class="btn btn-primary">Submit</button> | <a href="{% url 'workorders:index' %}">Cancel</a> </form> -
Create a form with one field with a model that has multiple fields
So, I want to log the searches which people make. To that end, I have this Search model: class Search(models.Model): search_string = models.CharField(max_length=40) ip_record = models.GenericIPAddressField() date_searched = models.DateTimeField(default=datetime.now()) Then, I have this form: class SearchForm(ModelForm): class Meta: model = Search fields = '__all__' How do I make it that there is only the search_string displayed? I have tried setting editable=False and using only the search_string field as a singleton list provided to fields, but that doesn't populate the other fields and creates an integrity error: IntegrityError at /endos/ NOT NULL constraint failed: backend_search.ip_record How should I be creating this form? And how do I create it with only one field and with the other fields being populated by computer? -
Edit base.css file from S3 Bucket
I'm using AWS S3 to serve my static files - however I've just found out you can't edit them directly from S3, which kind of makes it pointless as I will be continuously changing things on my website. So - is the conventional way to make the changes then re-upload the file? Or do most developers store their base.css file in their repository so it's easier to change? Because I'm using Django for my project so there is only supposed to be one static path (for me that's my S3 bucket) - or is there another content delivery network where I can directly edit the contents of the file on the go which would be better? -
Django Inline ManyToOne with Foreign key through third model
I am currently implementing a website some external packages. One of these (https://github.com/dj-stripe/dj-stripe) adds Customer and Cards to the Models. The Foreign keys are User <- Customer <- Card Customer has Customer.subscriber which is a foreign key to User and Card has Card.customer wich is a foreign key to Customer. I would like to Inline the Card to the UserAdmin, but the throughkeyword is only working for Many-To-Many Foreign Keys. I tried to do so by manipulating the get_queryset of the TabularInline Subclass, but this leads to check errors, because the desired fields are not part of the provided Model. class CustomerInline(admin.TabularInline): extra = 0 model = Customer readonly_fields = ('customer_id', 'stripe_id', 'last4') def get_queryset(self, request): customer_set = super(CustomerInline, self).get_queryset(request) qs = Card.objects.none() for customer in customer_set: qs = Card.objects.filter(customer=customer) return qs More general: How to inline a model admin with indirect foreign key connection?