Skip to main content

Posts

Showing posts with the label ManyRelatedManager

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: {% ...