Django ManyToMany Template Questions

Good morning,

I have been a PHP programmer for quite some time, but I felt the need to move more towards Python and which is better than playing with Django.

During the process, I came to a breakpoint where I know that there is a simple solution, but I just don’t see it - How to display many relationships in a Django template?

My Django Model: (most of the fields removed)

class Category(models.Model):
    name = models.CharField(max_length=125)
    slug = models.SlugField()   
categories = models.ManyToManyField(Category, blank=True, null=True)

class Recipe(models.Model):
    title = models.CharField('Title', max_length=250)
    slug = models.SlugField()

class Photo(models.Model):
    recipe = models.ForeignKey(Recipe)
    image = models.ImageField(upload_to="images/recipes", blank=True)

So, there are the main models that I use in my application called "recipes".
With that said, there are two questions I'm looking for answers to:

  • How can I show categories for a recipe on the details page?
  • How do I display an image for a recipe on the details page?

If I enter the Python shell and enter the following, I get the result:

>>> photos = Photo.objects.filter(recipe=1)
>>> photos
[<Photo: Awesome Pasta>]
>>> for photo in photos:
...     print "Photo: %s" % photo.logo
... 
Photo: images/recipes/2550298482_46729d51af__.jpg

- , " :" photo.image "."

{% for photo in photos %}
{% photo.image %}
{% endfor %}

, , - , ?

Page View.py snippet:

def details(request, slug='0'):
    p = get_object_or_404(Recipe, slug=slug)
    photos = Photo.objects.filter(recipe=1)
    return render_to_response('recipes/recipes_detail.html', {'p': p, 'photos': photos})

, , , !

UPDATE: Recipes.

+3
1

, , , :

{% photo.image %}

:

{{ photo.image }}

{% %} django. , {{ }}.

, , Photo Recipe. , Recipe, :

def details(request, slug='0'):
    p = get_object_or_404(Recipe, slug=slug)
    photos = p.photo_set.all()

, . , Django!

+3

Source: https://habr.com/ru/post/1714416/


All Articles