How to output fields to html template correctly from User model in Django ORM?
Task: Create a Django SQL query, pulling out only the required fields. Submit them to the template.
I have a Post model with a foreign key to a standard User model:
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
text = models.TextField()
pub_date = models.DateTimeField("date published", auto_now_add=True)
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="posts"
)
Here is the required fragment in the HTML template, where you need to insert the author's name:
{% for post in posts %}
<h3>
Author: {{ post.author.first_name }}, Date: {{ post.pub_date|date:'d M Y' }}
</h3>
view function:
from django.shortcuts import render
from .models import Post
def index(request):
latest = (
Post
.objects
.order_by('-pub_date')[:10]
.select_related('author')
.values('pub_date', 'author__first_name')
)
return render(request, 'index.html', {'posts': latest})
Here's what the page fragment looks like on the local server: template And here is the final sql query shown by django debug toolbar: Query
In the user table, I have one user and all posts are related to him. If I do not use .values in the view, then all the attributes of the author that I request in the template are displayed perfectly (for example, last_name, username, get_full_name()), but then sql requests all the fields of the user table (as it usually does), and I want get only certain ones to save memory. I also tried to recreate the project, use User = get_user_model(). Nothing helped.
You can refer this:
Model
from django.db import models
# Create your models here.
class CoachDetailsModel(models.Model):
coach_id=models.AutoField(primary_key=True)
name=models.CharField(max_length=100,help_text="Enter FullName")
email=models.EmailField(max_length=100,help_text="Enter Email id")
contact=models.BigIntegerField(help_text="Enter Mobile Number" ,null=True)
password=models.CharField(max_length=100,help_text="Enter Password")
coach_status=models.CharField(max_length=100,default='pending',help_text="Enter Password")
def __str__(self):
return self.email
class Meta:
db_table="Coach_details"
Views
def coach_register(request):
if request.method == "POST":
name= request.POST.get('name')
email = request.POST.get('email')
contact = request.POST.get('contact')
password = request.POST.get('password')
CoachDetailsModel.objects.create(name=name,email=email,contact=contact,password=password)
return render(request,'coach/coach-register.html')
### url
path('coach-register',coachviews.coach_register,name='coach_register'),
Html page
<form method="POST" id="contactForm" name="contactForm" class="contactForm" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="label" for="subject">Enter UserName</label>
<input type="text" class="form-control" name="name" id="subject" placeholder="UserName">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="label" for="subject">Enter Contact</label>
<input type="text" class="form-control" name="contact" id="subject" placeholder="Contact">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="label" for="subject">EMAIL-ADDRESS</label>
<input type="text" class="form-control" name="email" id="subject" placeholder="Email">
</div>
</div>
<div class="col-md-6">
<div class="form-group-col-6">
<label class="label" for="subject">PASSWORD</label>
<input type="text" class="form-control" name="password" id="subject" placeholder="Password">
</div>
</div>
<div class="col-md-12">
<div class="form-group col-9">
<input type="submit" value="Register" class="btn btn-primary">
<div class="submitting"></div>
</div>
</div>
</div>
</form>