简体   繁体   中英

how to access to foreign attributes model in django views

This is my code:

urls.py

url(r'^blog/$', views.blog, name='blog'),

models.py

class Category(models.Model):
  name = models.CharField(max_length=100)
  slug = models.CharField(max_length=100)
  description = models.CharField(max_length=200)
  creation_date = models.DateTimeField(auto_now_add=True)

class Post(models.Model):
  Status = ((1, "Publicado"), (2, "Borrador"), (3, "Eliminado"))
  status = models.IntegerField(choices=Status, default=3)
  title = models.CharField(max_length=100)
  slug = models.CharField(max_length=100, default='prueba')
  description = models.CharField(max_length=200)
  content = tinymce_models.HTMLField()
  category = models.ForeignKey(Category)
  creation_date = models.DateTimeField(auto_now_add=True)
  image = models.ImageField(upload_to="photos", default=1)
  autor = models.ForeignKey(User)

views.py

def blog(request):
  posts = Post.objects.filter(status=1).values().order_by("-creation_date")
  categories = Category.objects.order_by("name")
  context = {
    "posts":posts,
    "categories":categories
  }
  return render(request, "blog.html", context)

blog.html

{% for post in posts %}
  <a href="{% url 'detail_post' slug=post.slug %}">{{ post.title }}</a>
  <p>{{ post.description }}</p>
  <p>{{ post.category }}</p>
  <p>{{ post.autor }}</p>
  <p>{{ post.creation_date }}</p>
{% endfor %}

I can't access to the attributes author and category from a post. Please. I need help for how to do it. I need fix the problem. Thank you so much.

Try to do this in your template:

{% for post in posts %}
    <a href="{% url 'detail_post' slug=post.slug %}">{{ post.title }}</a>
    <p>{{ post.description }}</p>
    {% for category in post.category.all %}
        <p>{{ category.name }}</p>
    {% endfor %}
    {% for author in post.author.all %}
        <p>{{ author.name }}</p>
    {% endfor %}
    <p>{{ post.creation_date }}</p>
{% endfor %}

Hope this might help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM