Skip to main content

Posts

Showing posts with the label m2m

Django CMS custom Plugin ManyToMany fields problems.

Developing a website for Django CMS I have done a plugin. This plugin however have had a problem. It had an m2m field. While selecting images there (It was a gallery plugin). It was not saving it to production. This way main problem with this field was that plugin have displayed m2m choices on a draft page and while storing it to live it fails. Django CMS Pages is built like so it has multiple versions of pages. Each Page model that is changed is stored under new revision. And so plugin is copied and relinked to that page too. So plugin revisions multiply to. For e.g. in case you have a Draft page with two plugins that have model primary key number (pk in future) 12 and 14 accordingly. Say you hit publish changes. Not only PK of Page model rises and data are copypasted into new empty Page model instance. Those plugins are copied to. So mentioned plugins PK would change to 15 and 16 accordingly, assuming 14 is the latest plugin pk. New copied plugins will be linked to new page. Tha...

Django: 'ManyRelatedManager' object is not iterable

Upon development proces you often meet ManyToMany relations that throw errors in templates. I prefer to feed everything to context and play with it there. This kind of error appears when you iterate through a model's ManyToMany field. To fix it just add a related 'all' manager through dot syntax. Like so: Model: class BannerImage ( models . Model ) : image = models . ImageField ( upload_to = "somedir" ) def get_image_url ( self ) : return 'Image url here' class Banner ( models . Model ) : name = models . CharField ( max_length = 250 , null = True ) images = models . ManyToManyField ( BannerImage ) View/Tag or else, that creates context: banner = get_object_or_404 ( Banner , pk = 1 ) return { 'banner' : banner , } Template causing the error: {% for image in banner . images %} < img src = "{{ image.get_image_url }}" /> {% endfor %} Template without the error: {% ...