1

In the below code Instead of {{ i.user }} I want to access a value from another table with {{ i.user }} as matching value. How to done it within HTML

{% for i in obj reversed %}
<div class="container">
<blockquote>
    <header> {{ i.topic }} {{ i.user }} </header>
    <p> {{ i.desc }} </p>
    <footer> {{ i.time }} </footer>
</blockquote>
{% endfor %}
</div>

Here are My Models

from django.db import models

class Accounts(models.Model):
    name=models.CharField(max_length=30)
    phone=models.CharField(max_length=20,unique=True)
    mail=models.EmailField()
    password=models.CharField(max_length=20)

    def __str__(self):
        return self.name

class BlogPost(models.Model):
    user=models.CharField(max_length=30)
    topic=models.CharField(max_length=100)
    desc=models.CharField(max_length=1000)
    likes=models.IntegerField(null=True,default=0)
    time=models.DateTimeField(null=True)

    def __str__(self):
        return self.user

And I want to get value from Accounts using Blogspot.user i.e {{ i.user }} in template

Thanks in Advance...

5
  • Can you add your models ? Commented Sep 27, 2017 at 5:20
  • Added in Question Commented Sep 27, 2017 at 5:28
  • Inorder to have something like that you will need relations between models. use ForeignKey. How is your user field related to Accounts ? Commented Sep 27, 2017 at 5:33
  • user field in Blogspot matches to phone field in Accounts Models Commented Sep 27, 2017 at 5:35
  • There are couple of things. If you want to store details like password, email etc in django, better user Django's User model. Or you can override AbstractBaseUser. That way you can save lot of time/don't have to repeat code. Once a user model is set up, you can give foreignkey to User model from the BlogPost. Commented Sep 27, 2017 at 5:39

1 Answer 1

1
from django.contrib.auth.models import AbstractBaseUser

class Accounts(AbstractBaseUser):

    name = models.CharField(max_length=30)
    phone = models.CharField(max_length=20,unique=True)
    mail = models.EmailField()
    password = models.CharField(max_length=20)

    def __str__(self):
        return self.name

class BlogPost(models.Model):
    user = models.ForeignKey(Accounts, related_name='accounts')
    topic = models.CharField(max_length=100)
    desc = models.CharField(max_length=1000)
    likes = models.IntegerField(null=True,default=0)
    time = models.DateTimeField(null=True)

    def __str__(self):
        return self.user

Now, using foreign key you can access accounts model attributes in your template.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.