Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
coreapi action create, No current document
I'm trying to post using coreapi and Django Rest Framework. I'm following this tutorial, which is based on the official one. Coreapi download the schema in a folder (PATH) which is not the current one, instead of logging some info as in the tutorial. $ coreapi get http://127.0.0.1:8000/schema/ <DownloadedFile 'PATH', open 'rb'> Then: $ coreapi action snippets list No current document. Use `coreapi get` to fetch a document first. And similarly I'm not able to post: $ coreapi credentials add 127.0.0.1 admin:testpass123 --auth basic Added credentials 127.0.0.1 "Basic YWRtaW46d2lsbGlhbTE=" $ coreapi action snippets create --param title="Example" --param co de="print('hello, world')" No current document. Use `coreapi get` to fetch a document first. I've tried to copy the schema file in the current directory in which the "coreapi action" command is executed, but no improvements. -
Join three serializers django
Right now I have a RelatedFileSerializer and a RequirementsSerializer. When I query the RequirementsSerializer, I would like it to return all the relatedfiles, and all the User information (email, first name, last name) for the relatedfiles, in place of the user ID that is being returned from the fire serializer. It properly returns the related files right now, but not the user information... views.py queryset = Controls.objects.filter(requirement_version=requirement) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'first_name', 'last_name') class RelatedFileSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) class Meta: model = RelatedFiles fields = ('id', 'control', 'file', 'filename', 'uploaded_by_user', 'organization', 'note', 'uploaded_at') extra_kwargs = { 'uploaded_by_user': {'write_only': True}, 'organization': {'write_only': True}, } class RequirementsSerializer(serializers.ModelSerializer): relatedfiles_set = RelatedFileSerializer(many=True, read_only=True) class Meta: model = Controls fields = ('id', 'sorting_id', 'relatedfiles_set', 'requirement') -
Markdown is optional but my project already has Markdown 2.6 installed, get prepocessor error
I have Markdown 2.6 installed on my project and it is not feasible to update to version 3.0+ at this time. I see that Markdown 3.0+ is required, but because I have 2.6 it still successfully imports? As a result, in compat.py it successfully imports Markdown, however it breaks on line 213 because the highlight markdown preprocessor now uses register instead of add. The error is: Exception Type: AttributeError Exception Value: 'OrderedDict' object has no attribute 'register' Exception Location: /docker_venv/lib/python3.6/site-packages/rest_framework/compat.py in md_filter_add_syntax_highlight, line 213 How can I get around this? Is there a way to disable Markdown? Relevant issues/PRs I found: https://github.com/encode/django-rest-framework/pull/6722 https://github.com/encode/django-rest-framework/pull/6412 Thanks! -
how to pass a variable to a celery task
I want to pass a variable to a celery task, how to do this? From this code(POST method). class ArticleView(APIView): def get(self, request, task_id): task = current_app.AsyncResult(task_id) response_data = {'task_status': task.status,} if task.status == 'SUCCESS': response_data['results'] = task.get() return Response({"HTML-tags": response_data['results']}) def post(self, request): url = request.data.get('URL') print(url) task = demo.delay(url) return Response(task.id) To this: @shared_task def demo(url): page = requests.get(url) tree = html.fromstring(page.content) all_elms = tree.cssselect('*') all_tags = [x.tag for x in all_elms] baba = Counter(all_tags) return baba My attempt was unsuccessful.Error: TypeError: demo() takes 0 positional arguments but 1 was given. -
table "appname_modelname" already exists , migrate doesnt create new table
when i create a new model inside models.py and run : python manage.py makemigrations appname #worked python manage.py migrate #doesnt worked i got this error table "storage_OldModel" already exists i also checked this question Django migrate : doesn't create tables but there wasnt something to help me out this is the traceback please if someone know a solution please let me know -
Using filter_vertical or filter_horizontal for a CharField with choices
I'm searching for a way to use Django's .filter_vertical for a CharField (one that is passed a choices argument) rather than a ManyToManyField. Django's .filter_horizontal/.filter_vertical attributes produce a nice JavaScript "filter" interface in the admin UI: # models.py from django.db import models class Country(models.Model): code = models.SlugField(max_length=2, primary_key=True) name = models.CharField(max_length=64, db_index=True, unique=True) class MyModel(models.Model): countries = models.ManyToManyField(Country, blank=True) # ... other fields here # admin.py from django.contrib import admin @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): # ... other attributes here filter_vertical = ("countries",) This generates a form widget like: However, I'd like to use this for a CharField that is passed a list of choices: class MyModel(models.Model): countries = models.CharField( max_length=2, blank=True, choices=[ ("us", "United States"), ("tz", "Tanzania"), # and so on ] ) # ... other fields here This doesn't work as it stands, because .filter_horizontal and .filter_vertical requires that the field be a ManyToManyField. So, to rephrase the question a bit more specifically: since it looks like .filter_vertical and .filter_horizontal use a FilteredSelectMultiple widget for that field, how could I properly use this widget for a CharField? -
writing Django custom model field
I want to write a custom field that shows size of an item. like: "small", "medium", "large", "extra large". It have to be optional like IntegerField. this is what I want it to be. I don't know where and what should I do. -
Transforming HTML table populated by database query into matrix-like summary table
I have an HTML table that contains transaction-style information(date, category, and value) for each row. I would like to change this table from being a simple row-by-row table into a matrix-style summary table, taking in a group by query from my database and displaying the group by parameters as the column and row headers. Query: SELECT MONTH(date) as month, category, value FROM transactions GROUP BY month, category Current Table (using a query without the group by): Month || Category || Value ------------------------------ Jan || Produce || 10 Jan || Poultry || 20 Feb || Poultry || 30 Feb || Poultry || 20 Desired Table: || Jan || Feb ------------------------------ Produce || 10 || 0 Poultry || 20 || 50 I have no trouble reading the data into my table or displaying it, but I have been struggling to figure out how to format or display a table or some alternative HTML object in the matrix-style I have described. This is the HTML code to create my current table. I am using Django as my framework (hence the django syntax {{}} to populate my table). This does not seem like a Django problem to me, so I am not including any … -
django 2.2.5 URL regex in url path
I would like to support the above views in a single view in url ...in my search I came across [this post][1] which is no longer supported and all the tutorials i've found have been outdated, which demonstrate how to accomplish the task in django 1.8.3. In 'products/views.py' I have created a views for products and details. ProductListView will display all products, while ProductDetailView will display a single product detail (title, description, price etc). products/views.py class ProductListView(ListView): queryset = Product.objects.all() template_name = "products/list.html" class ProductDetailView(DetailView): queryset = Product.objects.all() template_name = "products/detail.html" products/urls.py include path to the views for ProductListView and ProductDetailView. ProductListView appears to be correct. ProductDetailView is incorrect! I'm getting the following warnings: WARNINGS: ?: (2_0.W001) Your URL pattern '^products/(?P\d+)/$' [name='details'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ecommerce.py/urls.py is where i've included products and details urls ecommerce/urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from .views import home, about, contact urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('about/', about, name='about'), path('products/', include('products.urls'), name='products'), path('products/', include('products.urls'), name='details'), path('contact/', contact, name='contact'), path('account/', … -
__init__() takes 1 positional argument but 2 were given. I'm getting this error in my django code
Views.py content import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from blog.models import Post, Comment from django.utils import timezone from blog.forms import PostForm, CommentForm from django.utils.decorators import method_decorator from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class PostUpdateView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blog/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('created_date') class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') I'm getting following error:- TypeError at /accounts/login/ init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 2.2.5 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: C:\Users\Hp\Anaconda3\envs\proenv\lib\site-packages\django\core\handlers\base.py in _get_response, line 113 Python Executable: C:\Users\Hp\Anaconda3\envs\proenv\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\Hp\Desktop\myproject\blog_project\mysite', 'C:\Users\Hp\Anaconda3\envs\proenv\python37.zip', 'C:\Users\Hp\Anaconda3\envs\proenv\DLLs', 'C:\Users\Hp\Anaconda3\envs\proenv\lib', 'C:\Users\Hp\Anaconda3\envs\proenv', 'C:\Users\Hp\Anaconda3\envs\proenv\lib\site-packages'] Server time: Tue, 17 Sep 2019 20:11:42 +0000 -
Django cannot serialize into migration file
Hi there i'm having problems when trying to use the command makemigrations with manage.py. The output is the following: Migrations for 'reg': reg\migrations\0012_auto_20190917_1711.py - Remove field Products from tenant - Add field products to tenant - Alter field productos on preaprobado - Alter field tenant_id on preaprobado - Alter field CMS_id on producto - Alter field CMS_id on tenant Traceback errors ValueError: Cannot serialize: <Producto: Basico - ['IPTEL', 'Rocstar', 'Test_DVT']> There are some values Django cannot serialize into migration files. For more, see https://docs.djangoproject.com/en/2.2/topics/migrations/#migration-serializing The thing is that the entire app works just fine but for some reason i can't understand i cannot migrate the db. Here is the models.py: class Producto(models.Model): Name = models.CharField(max_length = 50, unique = True) CMS_id = models.PositiveIntegerField(unique = True) def __str__(self): #Toma los tenants que tienen el producto asignado por el nombre y forma una lista de los nombres de los tenants #para que aparezcan al lado del nombre del producto tenants_with_product = Tenant.objects.filter(products__Name = self.Name) tenants_dict = tenants_with_product.in_bulk(field_name = "Name") tenants_list = [] for tenant_name in tenants_dict.keys(): tenants_list.append(tenant_name) return(self.Name + " - " + tenants_list.__str__()) class Tenant(models.Model): Name = models.CharField(max_length = 30, unique = True) Enabled = models.BooleanField(default = False) CMS_id = models.PositiveIntegerField(unique … -
Wagtail: How to override default ImageEmbedHandler?
I've been having some trouble implementing Wagtail CMS on my own Django backend. I'm attempting to use the 'headless' version and render content on my own SPA. As a result, I need to create my own EmbedHandlers so that I can generate URL's to documents and images to a private S3 bucket. Unfortunately, though I've registered my own PrivateS3ImageEmbedHandler, Wagtail is still using the default ImageEmbedHandler to convert the html-like bodies to html. Is there a way for me to set it so that Wagtail uses my custom EmbedHandler over the built in default? Here's my code: from wagtail.core import blocks, hooks from messaging.utils import create_presigned_url class PrivateS3ImageEmbedHandler(EmbedHandler): identifier = "image" @staticmethod def get_model(): return get_user_model() @classmethod def get_instance(cls, attrs): model = cls.get_instance(attrs) print(model) return model.objects.get(id=attrs['id']) @classmethod def expand_db_attributes(cls, attrs): image = cls.get_instance(attrs) print(image) presigned_url = create_presigned_url('empirehealth-mso', image.file) print(presigned_url) return f'<img src="{presigned_url}" alt="it works!"/>' @hooks.register('register_rich_text_features') def register_private_images(features): features.register_embed_type(PrivateS3ImageEmbedHandler) -
primary key 135 has an invalid foreign key: imageApp_webpage.topic_id contains a value 5 that doesn't have a corresponding value in imageApp topic.id
**from django.db import models from django.contrib.auth.models import User class Details(models.Model): name = models.CharField(max_length=264, unique=True) email = models.EmailField(max_length=50, unique=True) url = models.URLField(unique=True) class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) # author information portfolio = models.URLField(blank=True) image = models.ImageField(upload_to='CollectionImage/image', blank=True) def __str__(self): return self.user.username** I DON'T UNDERSTAND WHY I'M FACING THIS KIND OF PROBLEM. LIKE: bad_value, referenced_table_name, referenced_column_name django.db.utils.IntegrityError: The row in table 'imageApp_webpage' with primary key '135' has an invalid foreign key: imageApp_webpage.topic_id contains a value ' 5' that does not have a corresponding value in imageApp_topic.id. -
Python warnings to exceptions in Django tests with ignore
I'm attempting to run Django unit tests using: python -We -W ignore:DeprecationWarning -W ignore:UserWarning manage.py test However, this doesn't successfully ignore these warning classes, and instead only respects the -We flag, raising all warnings to exceptions. This is not my desired behavior. How can I run Django tests such that all warnings except DeprecationWarning and UserWarning are raised as exceptions when encountered in a test? -
How can I construct a Django Template Tag condition statement to check the request method for POST?
First, what I'd like to work: {% if method == POST %} {% include "app/template_x.html"%} {% else %} {% include "app/template_y.html"%} {% endif %} I'm using class based views, inheriting from django.views.generic.edit.UpdateView I tried a few things, among them passing an HttpRespons.method object via extra context in the urls.py asview() function. Anyone have an idea how I should approach this problem? -
heartbeat between python desktop app installed at client and django server app
There is a python desktop app that is deployed at client end and a Django web based server app. What way can we possibly set up a heartbeat for each client's desktop location so that we get an alert in case desktop application is not working/off. -
OSError: [Errno 99] Address not available - sending e-mail from django docker app with gmail smtp
I'm trying to send an e-mail from my django application in docker and I'm getting following error: OSError at /accounts/mail/ [Errno 99] Address not available Request Method: GET Request URL: https://localhost:8000/accounts/mail/ Django Version: 2.2.5 Exception Type: OSError Exception Value: [Errno 99] Address not available Web server log: web_1 | OSError: [Errno 99] Address not available web_1 | [17/Sep/2019 19:21:35] "GET /accounts/mail/ HTTP/1.1" 500 108369 My environment: Ubuntu 18.04 Docker Django + Gunicorn Postfix I have no problem to send an e-mail outside docker, locally. I suppose that there might be a problem with smtp port inside docker, but I don't know how to fix that. I tried with postfix - same error. View code from django: from django.core.mail import EmailMessage # didn't work also with send_mail def email(request): mail_subject = 'Activate your account' message = 'test' to_email = 'mail@mail' email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect('index') Part of my docker-compose file. version: '3.3' services: web: build: ./app command: python manage.py runsslserver 0.0.0.0:8000 ... ports: - 8000:8000 - 587:587 - 25:25 env_file: .envdev ... postfix: image: juanluisbaptiste/postfix:latest expose: - "25" env_file: - .envpostfix restart: always volumes: - "/etc/localtime:/etc/localtime:ro" ... Django settings: EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend EMAIL_USE_TLS=True EMAIL_HOST=smtp.gmail.com EMAIL_HOST_USER=*** EMAIL_HOST_PASSWORD=*** EMAIL_PORT=587 My … -
Items getting disappeared when I put them for scrollreveal
I'm using scroll reveal in my site. When I put them for scroll reveal they are getting disappeared. But first 4 items(images, div) are responding to the scroll reveal(2 or 3 items working fine) rest of the items are not. I'm using https://unpkg.com/scrollreveal/dist/scrollreveal.min.js. they are provided with exact id and classes for reveal method. <section style="margin-top: 60px; text-align: justify;"> <div class="container"> <div class="row"> <div class="col-md-4 col-sm-4"> <div class="cardss" style=" border-radius: 10px 10px 10px 10px;-moz-border-radius: 10px 10px 10px 10px;-webkit-border-radius: 10px 10px 10px 10px;padding: 10px"> <img id="im1" class="card-img-top" src="static/learninganddev.png" style="height: 250px; width: 200px; margin-left: 70px" alt="Card image cap"> <div class="card-body"> <h5 class="card-title" style="font-weight: 2px solid #000000; font-size: 20px">Learning&Development</h5> <p class="card-text">Google Home voice-activated speaker.consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p> </div> <div class="card-body" style="margin-top: 50px"> <a href="#" class="card-link">Read more</a> </div> </div> </div> <script> window.sr = ScrollReveal({ reset: true }); sr.reveal('.navbar', { duration: 2000, origin:'bottom' }); sr.reveal('.who', { duration: 2000, origin:'top', distance:'300px', easing: 'cubic-bezier(0.5, 0, 0, 1)' , }); sr.reveal('.whowearetext', { //till here everything is fine. duration: 2000, origin:'right', }); sr.reveal('.cardss', { // this one onwards not working, getting disappeared. … -
How do I assign a Python variable from js code to send to the database without reloading the page?
There is a page for creating posts "aframe". There is field name office 'title', button choice background, terrain. Data from the 'title' field is saved to the database. But how to connect the background, relief buttons to the database via django without reloading the page? Is it possible to pass a value from javascript to python to save to a database var sceneEl = document.querySelector('a-scene'); AFRAME.registerComponent('foo', { init: function () { var skyEl = sceneEl.querySelector('a-sky'); //Changing color using JQuery here $(document).ready(function(){ let color, src,mtl, terrain, text1; $("#text1").click(function(e){ var x = document.getElementById("fname").value; //document.write(x); document.getElementById("output").innerText = x; return false; }); $("#color button").click(function(e){ color = e.currentTarget.className; skyEl.setAttribute('src', '#blank'); skyEl.setAttribute('color', color); {{ background }} = color; }); $("#picture button").click(function(e){ src = e.currentTarget.className; skyEl.removeAttribute('color'); skyEl.setAttribute('src', '#'+src); }); $("#terrain button").click(function(e){ var skob = sceneEl.querySelectorAll('.obj_model'); terrain = e.currentTarget.className; mtl = e.currentTarget.name; for (let index = 0; index <= skob.length; ++index) { //alert(mtl); //skyEl.setAttribute('color', '#1fa9e3'); skob[index].setAttribute('src', '#'+terrain+'-obj'); skob[index].setAttribute('mtl', '#'+mtl); if(terrain=='city'){ skob[index].setAttribute('scale', '30 120 35'); } else { skob[index].setAttribute('scale', '5 10 5') ; } } }); }); } }); sourceURL=pen.js <form method="post"> <div id="left" > <div id="select"> <div id="cssmenu"> {% csrf_token %} <input type="text" placeholder="title" name="title"> <input type="text" placeholder="body" name="body"> <input type="text" placeholder="background" name="background"> <ul> <li class='has-sub'><a href='index.html'><span>Terrain</span></a> <ul> … -
Django background task not running
I am trying to run a background task in django to run an sql query when the user clicks on a certain button. I created the function in tasks.pyand when I try and run it using the @background decorator, it does not run (Runs fine without @background). I am not getting any error, however the task is not running. Here is my tasks.py from background_task import background from django.db import connection @background(schedule=1) def delete_process_background(process_id): print("Start of background task") with connection.cursor() as cursor: cursor.callproc("delete_process",[process_id]) And my function in views.py that is triggered when user clicks the button: def db_revert_process(request): process_id = int(request.POST['text']) delete_process_background(process_id) print("Called background process") return HttpResponse() The print statement in the views.py function is executed but not the statement in the background task. -
django models: change the way value of a field gets rendered in admin panel
My model in django has uuid as its primary key: class User(models.Model): token = models.UUIDField(primary_key=True, default=uuid.uuid4) def __str__(self): return str(self.token).replace('-', '') and since uuid gets saved in the database without dashes(-), therefor I could able to render it without dashes using __str__ in the code above. The result looks like this: But how can I do the same thing for the way the value gets rendered in the admin panel (how to remove dashes): -
django form can not find the author in the post
Wanted to have every user already post with their post authorship but, the code I have with, they need to choose the author I have tried deleting author then error pop up: author_id is unknown class Post(models.Model): STATUS_CHOICES = { ("draft", "Draft"), ("published", "Published"), } author = models.ForeignKey(User, on_delete = models.CASCADE, default = 1 ) title = models.CharField(max_length= 100, null=True, blank=True, default="Başlık") class PostForm(forms.ModelForm): class Meta: model = Post fields = ["author", "title", "content", "image"] widgets = { "author": forms.Select(attrs={"class": "form-control"}), "title": forms.TextInput(attrs={"class": "form-control"}), I use django 2.2.5 and still have errors -
How to search by choice value
How to search by choice value and not the key as in the following: This model: CITY_CHOICES = ( ('Omran', 'عمران'), ('AlBayda ', 'البيضاء'), ('Hodeidah', 'الحديدة'), ) class Place(models.Model): city = models.CharField(choices=CITY_CHOICES, max_length=20) # Manager objects = PlaceManager() This search by city but looking for the key and I want it looking for value class PlaceQuerySet(models.QuerySet): def search(self, query): lookup = ( Q(city__icontains=query) ) return self.filter(lookup) class PlaceManager(models.Manager): def get_queryset(self): return PlaceQuerySet(self.model, using=self._db) def search(self, query=None): if query is None: return self.get_queryset().none() return self.get_queryset().search(query) -
How to retreive manyToMany field in django model serializer, with viewset?
Help, I am trying to understand since last hours, how to send a manytomany extra data with my Item modelSerializer. here is the definition of the fiel in the Item model, extra = models.ManyToManyField(SimpleExtraField, through='ExtraField') class ExtraField(models.Model): item = models.ForeignKey(Item, related_name="extra_fields") key = models.ForeignKey(SimpleExtraField) # add limit to not yet selected value = models.CharField(max_length=glLargeCharLen) here is my model serializer : class basic_itemSerial(serializers.ModelSerializer): medias = mediaSerial(many=True) extra = ExtraSerial(many=True, required=False) children = minItemSerial(many=True) class Meta: model = Item fields = '__all__' as a queryset, I am just trying to get a list, list this queryset = Item.objects.all() I tried adding extra data to get_serializer_context, like this, def get_serializer_context(self, *args, **kwargs): context = super(self.__class__, self).get_serializer_context(*args, **kwargs) qex= [] for q in self.queryset: qq = ExtraField.objects.all().filter(item=q.reference) for qqs in qq: qex.append(qqs) context['extra'] = qex return context I also tried to change the name in the serializer to extra_fields = ExtraSerial(many=True, required=False) But None of them worked for me, I think I am connecting bad the serializer to the queryset. also here are the extraModel and SimpleExtraField: class ExtraField(models.Model): item = models.ForeignKey(Item, related_name="extra_fields") key = models.ForeignKey(SimpleExtraField) # add limit to not yet selected value = models.CharField(max_length=glLargeCharLen) serializer.py class SimpleExtraField(models.Model): name = models.CharField(max_length=glMiddleCharLen, unique=True, primary_key=True) -
How to get values for a queryset for an model when the foreign key is not in the current model?
I have the following models: class Work_Music(models.Model): key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) class Catalogue(models.Model): work_music = models.ForeignKey(Work_Music, verbose_name=_('work_music'), on_delete=models.PROTECT) name = models.CharField(max_length=100, null=True, blank=True) name_short = models.CharField(max_length=100, null=True, blank=True) no = models.CharField(max_length=100, null=True, blank=True) related_field() only works with the Foreign key is in Work_Music. Many catalogue/catalogue numbers can map to a piece of music (Work_Music). How can I construct a query set on Work_Music to pull all of the catalogues related to the piece of work?