Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?

2024/9/8 9:06:00

I've got a couple django models that look like this:

from django.contrib.sites.models import Siteclass Photo(models.Model):title = models.CharField(max_length=100)site = models.ForeignKey(Site)file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self):return self.titleclass Gallery(models.Model):    name = models.CharField(max_length=40)site = models.ForeignKey(Site)photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} )    def __unicode__(self):return self.name

I'm having all kinds of fun trying to get the limit_choices_to working on the Gallery model. I only want the Admin to show choices for photos that belong to the same site as this gallery. Is this possible?

Answer

Yes. You need to override the form that admin uses for the Gallery model, then limit the queryset of the photos field in that form:

class GalleryAdminForm(django.forms.ModelForm):class Meta:model = Gallerydef __init__(self, *args, **kwargs):super(GalleryAdminForm, self).__init__(*args, **kwargs)self.fields['segments'].queryset = Photo.objects.filter(site=self.instance.site)class GalleryAdmin(django.contrib.admin.ModelAdmin):form = GalleryAdminFormdjango.contrib.admin.site.register(Gallery, GalleryAdmin)
https://en.xdnf.cn/q/72624.html

Related Q&A

Logging django.request to file instead of console

I am trying to configure my django settings.py to properly use the python logging facility but Ive stumbled upon a rather strange problem:Even after reading the docs, I simply cant find out how to redi…

Coinbase APIerror(id = ) in python

I want to transfer money between my coinbase accounts. Im storing all of my accounts IDs from client.get_accounts()[data][id] and transferring with the code, tx = client.transfer_money(2bbf394c-193b-5b…

cxfreeze missing distutils module inside virtualenv

When running a cxfreeze binary from a python3.2 project I am getting the following runtime error:/project/dist/project/distutils/__init__.py:13: UserWarning: The virtualenv distutils package at %s appe…

Preventing a multiplication expression evaluating in Sympy

I am generating an expression with two fractions, and want to pretty print as a whole expression with LaTeX, to then put on a worksheet.E.g. in the form:(5/7) * (3/4). However, when I do the following:…

Calling PARI/GP from Python

I would like to call PARI/GP from Python only to calculate the function nextprime(n) for different ns that I define. Unfortunately I cant get pari-python to install so I thought I would just call it us…

Can anyone explain why this sorting wont work?

For example if I have a list like this:List1 =[7,6,9] List1 = List1.sort()

Using argparse for mandatory argument without prefix

Im trying to use argparse module within my python application. My application should be run with single mandatory argument without any prefixes. I could not come up with a way to do it.

prevent unexpected stdin reads and lock in subprocess

A simple case Im trying to solve for all situations. I am running a subprocess for performing a certain task, and I dont expect it to ask for stdin, but in rare cases that I might not even expect, it m…

Regex split string by last occurrence of pattern

I am using regex to split a string <book name> by <author name> into book and author names.re.split(r\bby\b, text, 0, re.I)But problem arises when the book name contains the word "by&q…

How to write a unit-test where each test case has different input but does the same?

I need to create a unit-test for some python class. I have a database of inputs and expected results which should be generated by the UUT for those inputs.Here is the pseudo-code of what I want to do:f…