I'm writing a simple real-estate listing app in Django. Each property needs to have a variable number of images. Images need to have an editable order. And I need to make the admin user-proof.
So that said, what are my options?
Is there a ImageList field that I don't know about?
Is there an app like django.contrib.comments that does the job for me?
If I have to write it myself, how would I go about making the admin-side decent? I'm imagining something a lot slicker than what ImageField provides, with some drag'n'drop for re-ordering. But I'm a complete clutz at writing admin pages =(
Variable lists, also known as a many-to-one relationship, are usually handled by making a separate model for the many and, in that model, using a ForeignKey to the "one".
There isn't an app like this in django.contrib, but there are several external projects you can use, e.g. django-photologue which even has some support for viewing the images in the admin.
The admin site can't be made "user proof", it should only be used by trusted users. Given this, the way to make your admin site decent would be to define a ModelAdmin for your property and then inline the photos (inline documentation).
So, to give you some quick drafts, everything would look something like this:
# models.py
class Property(models.Model):
address = models.TextField()
...
class PropertyImage(models.Model):
property = models.ForeignKey(Property, related_name='images')
image = models.ImageField()
and:
# admin.py
class PropertyImageInline(admin.TabularInline):
model = PropertyImage
extra = 3
class PropertyAdmin(admin.ModelAdmin):
inlines = [ PropertyImageInline, ]
admin.site.register(Property, PropertyAdmin)
The reason for using the related_name argument on the ForeignKey is so your queries will be more readable, e.g. in this case you can do something like this in your view:
property = Property.objects.get(pk=1)
image_list = property.images.all()
EDIT: forgot to mention, you can then implement drag-and-drop ordering in the admin using Simon Willison's snippet Orderable inlines using drag and drop with jQuery UI
Write an Image model that has a ForeignKey to your Property model. Quite probably, you'll have some other fields that belong to the image and not to the Property.
I'm currently making the same thing and I faced the same issue.
After I researched for a while, I decided to use django-imaging. It has a nice Ajax feature, images can be uploaded on the same page as the model Insert page, and can be editable. However, it is lacking support for non-JPEG extension.
There is a package named django-galleryfield. I think it will meet your demand.
Related
I'm evaluating Wagtail to see if I can find a place for it along side Wordpress and Drupal in my company. So far I think it's interesting and really like a lot of it, but there's one thing I would really like and can't find a way to do it.
My shop uses a pattern library (a la Atomic Design) and initially I was excited by the StreamField and it's ability to tie directly in to a pattern library, including creating nested patterns (a reusable button class that can be put in a CTA and a Hero Widget. But the stream field doesn't work for required page elements that have to be in a certain location, possibly outside the content flow (hero content, calls to action...).
I found this issue: https://github.com/wagtail/wagtail/issues/2048
But it doesn't seem to be resolved and hasn't had activity in a long time.
Right now I've found two possible solutions:
A stream field with only one block possible, and a min and max of one of them.
The drawback is that the UI doesn't seem to be aware of the min/max and you have to save the page before you're told. Also, the form isn't automatically visible, you still have to click the CTA button. This would be too confusing for my users (and I can't make the case to my shop since this isn't a problem in WP and Drupal).
A Foreign Key to a Django Model, using the InlinePanel and requiring a single instance.
The drawback here is that the user still sees a grayed out add button and still sees the delete button for the field data, which they can do, then the page doesn't validate on save.
I've seen a BlockField in the source code, but there's absolutely no docs on how to use it, it seems like such a thing would solve my problems, but I can't get it to work.
Am I missing something? Is there a way to create a reusable set of fields that I can easily attach to page types, and cause the fields to be visible on page load and presented in a way that users will understand right away?
Define your common fields in an abstract base model, and inherit from that in your page classes whenever you want to use them:
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.core.fields import RichTextField
from wagtail.core.models import Page
class HeroFields(models.Model):
hero_image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+')
hero_url = models.URLField()
hero_field_panels = [
FieldPanel('hero_image'),
FieldPanel('hero_url'),
]
class Meta:
abstract = True
class HomePage(Page, HeroFields):
body = RichTextField()
content_panels = Page.content_panels + HeroFields.hero_field_panels + [
FieldPanel('body'),
]
Let's say I have these two models:
class Egg(models.Model):
# some fields
class Spam(models.Model):
egg = models.ForeignKey(Egg)
img = models.ImageField()
I planned to have the spams inlined to egg in admin site. The problem is I also want a very customized method on uploading the spam images (like this), like having my own view and template. So far, I just got :
class CustomInline(admin.StackedInline):
model = Spam
template = 'admin/app/inline.html' # empty
class EggAdmin(admin.ModelAdmin):
inlines = [CustomInline, ]
The idea is having some kind of gallery of spams and custom image upload in egg admin. (Is this achievable?)
So the questions are:
I want to injects variables to be available on the template (spam objects on inline.html for gallery) . Is there a way to do this?
Is it okay to POST something to a view (upload process)? Or that particular view must be registered first on admin site or something?
I've looked on InlineAdmin source but still have no idea what to do/override
Thanks
using the form property you can subclass your ModelForm and completely change the way your inline form works.
So I've got a UserProfile in Django that has certain fields that are required by the entire project - birthday, residence, etc. - and it also contains a lot of information that doesn't actually have any importance as far as logic goes - hometown, about me, etc. I'm trying to make my project a bit more flexible and applicable to more situations than my own, and I'd like to make it so that administrators of a project instance can add any fields they like to a UserProfile without having to directly modify the model. That is, I'd like an administrator of a new instance to be able to create new attributes of a user on the fly based on their specific needs. Due to the nature of the ORM, is this possible?
Well a simple solution is to create a new model called UserAttribute that has a key and a value, and link it to the UserProfile. Then you can use it as an inline in the django-admin. This would allow you to add as many new attributes to a UserProfile as you like, all through the admin:
models.py
class UserAttribute(models.Model):
key = models.CharField(max_length=100, help_text="i.e. Age, Name etc")
value = models.TextField(max_length=1000)
profile = models.ForeignKey(UserProfile)
admin.py
class UserAttributeInline(admin.StackedInline):
model = UserAttribute
class UserProfile(admin.ModelAdmin):
inlines = [UserAttibuteInline,]
This would allow an administrator to add a long list of attributes. The limitations are that you cant's do any validation on the input(outside of making sure that it's valid text), you are also limited to attributes that can be described in plain english (i.e. you won't be able to perform much login on them) and you won't really be able to compare attributes between UserProfiles (without a lot of Database hits anyway)
You can store additional data in serialized state. This can save you some DB hits and simplify your database structure a bit. May be the best option if you plan to use the data just for display purposes.
Example implementation (not tested)::
import yaml
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField('auth.User', related_name='profile')
_additional_info = models.TextField(default="", blank=True)
#property
def additional_info(self):
return yaml.load(self._additional_info)
#additional_info.setter
def additional_info(self, user_info_dict):
self._additional_info = yaml.dump(user_info_dict)
When you assign to profile.additional_info, say, a dictionary, it gets serialized and stored in _additional_info instead (don't forget to save the instance later). And then, when you access additional_info, you get that python dictionary.
I guess, you can also write a custom field to deal with this.
UPDATE (based on your comment):
So it appears that the actual problem here is how to automatically create and validate forms for user profiles. (It remains regardless on whether you go with serialized options or complex data structure.)
And since you can create dynamic forms without much trouble[1], then the main question is how to validate them.
Thinking about it... Administrator will have to specify validators (or field type) for each custom field anyway, right? So you'll need some kind of a configuration option—say,
CUSTOM_PROFILE_FIELDS = (
{
'name': 'user_ip',
'validators': ['django.core.validators.validate_ipv4_address'],
},
)
And then, when you're initializing the form, you define fields with their validators according to this setting.
[1] See also this post by Jacob Kaplan-Moss on dynamic form generation. It doesn't deal with validation, though.
I'm a little confused as to why this sort of functionality isn't default in the admin, but maybe someone can give me a few hinters to how to go about it.
I have a projects application which keeps track of projects and is to be edited through the admin. Each project has numerous ForeignKey related models (links, flatpages, video, image etc.) that could be placed as inlines within the project admin.
(One or two models have nested inlines, so they don't display in the admin (this and this ticket deal with this) )
Instead of being able to edit these models inline on the project admin (which gets messy and difficult to use), I would love a list of all the current instances of that related model, and simple add/edit button for each model which opens a popup with that model's form.
Project Admin:
- Normal Fields
- Links:
-Link 1 (edit)
-Link 2 (edit)
+ add link <- popup
- Images:
-Image 1 (edit)
-Image 2 (edit)
+ add image <- popup
so on. How would I go about writing this? I only need to do it for one section/model of the admin panel so I don't think writing my own Crud backend is necessary.
Thanks
I implemented something like this in an application once, but since django-admin doesnt support nested inlines (by which i mean inlines within inlines), i followed a slightly different approach. The use case was that you had an invoice (with a few inline attributes) and u had reciepts (again with inline attributes). Reciepts had a foreign key to the invoice model (basically a reciept was part payment of the invoice).
I implemented it by adding a field to the invoice list view which linked to a filtered reciept list view.
So in the invoice admin, there would be:
def admin_view_receipts(self, object):
url = urlresolvers.reverse('admin:invoice_%s_changelist'%'receipt')
params = urllib.urlencode({'invoice__id__exact': object.id})
return 'Receipts' % (url, params)
admin_view_receipts.allow_tags = True
admin_view_receipts.short_description = 'Receipts'
This gives you a link in the list view that takes you to another list view, but filtered by foreignkey. Now you can have inlines for both models and easy access to the related models.
Consider a wiki application. There is a model Page, that has many Revisions and each revision has many blocks.
What is the simplest way to create an admin in which, you select a page and all the blocks of the latest revision appear; bonus points for letting change of revision by a dropdown (which is by default, sorted in reverse order anyway)
Is it absolutely necessary to create views, or can I extend some of those StackedInline forms, override save and mention some magic meta options, to get it all done automagically.
Have you tried something like this (in admin.py):
class RevInline(admin.TabularInline):
model = Revision
class PageAdmin(admin.ModelAdmin):
model = Page
inlines = (RevInline,)
admin.site.register(Page, PageAdmin)