I'm developing a portfolio application. Within this application, I have a model called "Project" which looks something like this:
class Project(models.Model):
...
images = models.ManyToManyField(Image)
...
so, basically, this Project can contain a set of images (any of these images may belong to another Project as well).
Now, what I'd like to add is a way of specifying that one of these "images" is a "lead_image".
So I could add something like this:
class Project(models.Model):
...
images = models.ManyToManyField(Image, related_name='images')
lead_image = models.ForeignKey(Image, related_name='lead_image')
...
However, the problem with this is that in this case, lead_image can be ANY image. What I really want is for it to be one of the "images" that belongs to to this model instance.
I'm thinking that I need to use "ForeignKey.limit_choices_to" argument, but I'm unsure of how to use this...especially since when the model instance is first created, there won't yet be any images in the "images" directory.
Any help would be greatly appeciated.
Doug
If you're wanting to achieve the limiting effect in the admin tool, you can override the formfield-for-foreignkey method and insert your own filter.
class ProjectAdmin(admin.ModelAdmin):
# ...
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "lead_image":
kwargs["queryset"] = self.model.images.all()
return db_field.formfield(**kwargs)
return super(ProjectAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
The problem I see here (with this general idea of only picking from picked images) is that for new models, initially model.images won't be set when the page loads. You'll probably face this problem no matter what server-side trick you go with.
It could work, but it requires an extra click: When the model is first created the ManyToMany model.images will be picked. After picked, if "Save and Continue" is clicked, then those images should appear in the model.lead-image FK field.
Your other option would be to override the default admin form and create something custom (custom as in custom fancy-pants javascript to auto-update the 'lead image' field combo box).
Another approach to your problem is to use a intermediate table with a boolean property 'is_lead_image'.
class Image(models.Model):
...
class Project(models.Model):
images = models.ManyToManyField(Image, through='ProjectImage')
...
class ProjectImage(models.Model):
image = models.ForeignKey(Image)
project = models.ForeignKey(Project)
is_lead_image = models.Boolean(default=False)
def save(self, *args, **kwargs):
if self.is_lead_image:
self._default_manager.filter(project=self.project).update(is_lead_image=False)
return super(ProjectImage, self).save(*args, **kwargs)
*Note: If you like and if you have access you can also just add the is_lead_image field and the save directly to the Image class.
Related
I want to implement kind of row level security for my model in Django. I want to filter out data as low as it's possible based on some requirement.
Now, I know I could create specified managers for this model as docs says but it seems for me that it needs to be static. I also know that I can create just method that will return queryset as I want but I'll be not sufficient, I mean the possibility to just get all data is still there and the simplest mistake can lead to leak of them.
So I found this post but as author said - it's not safe nor pretty to mess around with global states. This post is nearly 10 years old so I hope that maybe someone has come up with a better generic solution.
Here is piece of example to visualise what I need:
models.py:
class A(models.Model):
...
class B(models.Model):
user = models.ForeignKey(User)
a = models.ForeignKey(A)
And I want to create global functionality for getting objects of A only if instance of B with user as logged in user exists.
I came up with solution to just override get_queryset() of A manager like so:
managers.py
class AManager(models.Manager):
def get_queryset(self):
return super().get_queryset(b__user=**and_here_i_need_a_user**)
but I can't find hot to parametrize it.
==== EDIT ====
Another idea is to simply not allow to get querysets of A explicitly but only via related field from B but I can't find any reference how to accomplish that. Has anyone done something like that?
So you're sort of on the right track. How about something like this...
class AQuerySet(models.QuerySet):
def filter_by_user(self, user, *args, **kwargs):
user_filter = Q(b__user=user)
return self.filter(user_filter, *args, **kwargs)
class AManager(models.Manager):
queryset_class = AQuerySet
def filter_by_user(self, user, *args, **kwargs):
return self.get_queryset().filter_by_user(user, *args, **kwargs)
class A(models.Model):
objects = AManager()
# ...
then you can use it like this:
A.objects.filter_by_user(get_current_user(), some_filter='some_value')
I want to create an extra manager for fetching a filtered version of a reverse ManyToMany relationship. I have these models:
class Photo(models.Model):
# ...
is_public = models.BooleanField()
albums = models.ManyToManyField('Album')
class Album(models.Model):
# ...
I can get all the photos in an album with album.photo_set.all(). I'd like to provide a way to get only the public photos in an album by doing album.photo_set.public() (which would, somewhere, do a .filter(is_public=True)).
I guess I'm wanting to provide an extra Related manager, but I'm not sure that's possible. I don't want, or need, to replace the default related manager (which sounds like a bad idea anyway). I don't need a custom through model for the relationship, unless that's the only way to achieve this.
Sure, you could make a related manager but that seems a bit overkill for this.
Why not just simply add a function to your model that returns only the public photos in the album?
def get_public(self):
return self.photo_set.filter(is_public = True)
You can create manager like this:
class PublicManager(models.Manager):
use_for_related_fields = True
def public(self, *args, **kwargs):
kwargs.update({
'is_public': True
})
return self.get_queryset().filter(*args, **kwargs)
How can I override the value that is displayed for a field in the Django admin? The field contains XML and when viewing it in the admin I want to pretty-format it for easy readability. I know how to do reformatting on read and write of the field itself, but this is not what I want to do. I want the XML stored with whitespace stripped and I only want to reformat it when it is viewed in the admin change form.
How can I control the value displayed in the textarea of the admin change form for this field?
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.initial['some_field'] = some_encoding_method(self.instance.some_field)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
...
Where, some_encoding_method would be something you've set up to determine the spacing/indentation or some other 3rd-party functionality you're borrowing on. However, if you write your own method, it would be better to put it on the model, itself, and then call it through the instance:
class MyModel(models.Model):
...
def encode_some_field(self):
# do something with self.some_field
return encoded_some_field
Then:
self.instance.encode_some_field()
Given a model with ForeignKeyField (FKF) or ManyToManyField (MTMF) fields with a foreignkey to 'self' how can I prevent self (recursive) selection within the Django Admin (admin).
In short, it should be possible to prevent self (recursive) selection of a model instance in the admin. This applies when editing existing instances of a model, not creating new instances.
For example, take the following model for an article in a news app;
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
related_articles = models.ManyToManyField('self')
If there are 3 Article instances (title: a1-3), when editing an existing Article instance via the admin the related_articles field is represented by default by a html (multiple)select box which provides a list of ALL articles (Article.objects.all()). The user should only see and be able to select Article instances other than itself, e.g. When editing Article a1, related_articles available to select = a2, a3.
I can currently see 3 potential to ways to do this, in order of decreasing preference;
Provide a way to set the queryset providing available choices in the admin form field for the related_articles (via an exclude query filter, e.g. Article.objects.filter(~Q(id__iexact=self.id)) to exclude the current instance being edited from the list of related_articles a user can see and select from. Creation/setting of the queryset to use could occur within the constructor (__init__) of a custom Article ModelForm, or, via some kind of dynamic limit_choices_to Model option. This would require a way to grab the instance being edited to use for filtering.
Override the save_model function of the Article Model or ModelAdmin class to check for and remove itself from the related_articles before saving the instance. This still means that admin users can see and select all articles including the instance being edited (for existing articles).
Filter out self references when required for use outside the admin, e.g. templates.
The ideal solution (1) is currently possible to do via custom model forms outside of the admin as it's possible to pass in a filtered queryset variable for the instance being edited to the model form constructor. Question is, can you get at the Article instance, i.e. 'self' being edited the admin before the form is created to do the same thing.
It could be I am going about this the wrong way, but if your allowed to define a FKF / MTMF to the same model then there should be a way to have the admin - do the right thing - and prevent a user from selecting itself by excluding it in the list of available choices.
Note: Solution 2 and 3 are possible to do now and are provided to try and avoid getting these as answers, ideally i'd like to get an answer to solution 1.
Carl is correct, here's a cut and paste code sample that would go in admin.py
I find navigating the Django relationships can be tricky if you don't have a solid grasp, and a living example can be worth 1000 time more than a "go read this" (not that you don't need to understand what is happening).
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myManyToManyField'].queryset = MyModel.objects.exclude(
id__exact=self.instance.id)
You can use a custom ModelForm in the admin (by setting the "form" attribute of your ModelAdmin subclass). So you do it the same way in the admin as you would anywhere else.
You can also override the get_form method of the ModelAdmin like so:
def get_form(self, request, obj=None, **kwargs):
"""
Modify the fields in the form that are self-referential by
removing self instance from queryset
"""
form = super().get_form(request, obj=None, **kwargs)
# obj won't exist yet for create page
if obj:
# Finds fieldnames of related fields whose model is self
rmself_fields = [f.name for f in self.model._meta.get_fields() if (
f.concrete and f.is_relation and f.related_model is self.model)]
for fieldname in rmself_fields:
form.base_fields[fieldname]._queryset =
form.base_fields[fieldname]._queryset.exclude(id=obj.id)
return form
Note that this is a on-size-fits-all solution that automatically finds self-referencing model fields and removes self from all of them :-)
I like the solution of checking at save() time:
def save(self, *args, **kwargs):
# call full_clean() that in turn will call clean()
self.full_clean()
return super().save(*args, **kwargs)
def clean(self):
obj = self
parents = set()
while obj is not None:
if obj in parents:
raise ValidationError('Loop error', code='infinite_loop')
parents.add(obj)
obj = obj.parent
A have 3 models: Project, Image and Video with ManyToManyField relation:
class Project(models.Model):
images = models.ManyToManyField('Image', through='Project_Images')
video = models.ManyToManyField('Video', through='Project_Video')
class Image(models.Model):
original = models.ImageField()
projects = models.ManyToManyField('Project', through='Project_Images')
class Video(models.Model):
projects = models.ManyToManyField('Project', through='Project_Video')
I configure project's admin form with inline forms of Images and Videos linked to current project:
class ProjectAdmin(admin.ModelAdmin):
inlines = [VideoInline, ImagesInline]
class ImagesInline(admin.TabularInline):
model = Project_Images
raw_id_fields = ['project','image']
class VideoInline(admin.TabularInline):
model = Project_Video
raw_id_fields = ['project','video']
But inline table with simple select field and delete checkbox is much miserable for me, and I want to show here previews of images or video (youtube). I solve this for images with help of AdminImageWidget:
class ImageForm(forms.ModelForm):
class Meta:
model = Image
preview = forms.ImageField(widget=AdminImageWidget())
def __init__(self, *args, **kwargs):
super(ImageForm, self).__init__(*args, **kwargs)
try:
image = Image.objects.get(id=self.instance.image_id)
self.fields["preview"].initial = image.original
except:
pass
class ImagesInline(admin.TabularInline):
.....
form = ImageForm
Is it best way to do this? In my case I don't need file upload input, only image-preview in inline form table. I need also preview for youtube video, should I write my own widget for displaying video and apply it to some fake field ?
It's strange to solve this issue by widget for unnecessary fake field. Or is it normal way?
Any help will be very much appreciated!
Thanks!
You should create a widget similar to AdminImageWidget but that displays only the image, not the upload box. To apply that widget you don't need a custom Form class or a fake field, just use formfield_overrides on your ImageInline:
class ImageInline(admin.TabularInline):
...
formfield_overrides = { models.ImageField: {'widget': YourPreviewWidget}}
EDIT: Oops, didn't fully process the ManyToManyField issue - you're displaying inlines for the "through" table, not the table with the actual ImageFields. Given that, what you're doing now may be not such a bad solution. The alternative I can think of would be to write a specialized replacement widget for the Select, that knows how to display both the select box and a preview image for the currently selected Image object. That way you could avoid the need for the fake extra field.