HOW TO GET DJANGO MODELS FIELD VALUE FROM MODEL OBJECT IN TEMPLATE TAGS-DJANGO

41 views
Skip to first unread message

Kala Rani

unread,
Nov 6, 2022, 6:15:35 AM11/6/22
to Django users
my models.py

class Locations(models.Model):
region = models.ForeignKey(Regions, on_delete=models.CASCADE,blank=True,null=True)
name = models.CharField(max_length=255)
active_flag = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now=True)

def __str__(self):
return self.name


class Regions(models.Model):
region_name = models.CharField(max_length=255)
working_hours_per_day = models.CharField(max_length=255,null=True)
days_per_week = models.CharField(max_length=255,null=True)
hours_per_week = models.CharField(max_length=255,null=True)
week_per_month = models.CharField(max_length=255,null=True)
hours_per_month = models.CharField(max_length=255,null=True)
days_per_year = models.CharField(max_length=255,null=True)
weeks_per_year = models.CharField(max_length=255,null=True)
active_flag = models.BooleanField(default=True)
show_flag = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now=True)

def __str__(self):
return self.region_name


views.py

def center(request):
locations = Locations.objects.select_related('region')
td_serializer = LocationSerializer(locations,many=True)
x=td_serializer.data
data = {
'td':td_serializer.data,
#'centers':center_serializer.data,
}
return response.Response(data,status.HTTP_200_OK)




template:

fetchLocationsList(){
this.$axios.$post('/projects/chcenter',config).then(response => {
if(response){
this.locations =response.td;
for(let i=0;i <this.locations.length; i++){
this.x=this.locations[i].name
this.y=this.locations[i].region
this.z=this.y + "-" +this.x
this.result.push(this.z)


How to get region_name ?




Sebastian Jung

unread,
Nov 6, 2022, 10:01:42 AM11/6/22
to django...@googlegroups.com
Pls write us your aim with this code...

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3a93ef8a-4fc6-48a8-83d7-cc4ea65ae649n%40googlegroups.com.

Kala Rani

unread,
Nov 6, 2022, 10:26:54 PM11/6/22
to Django users
I want to get region_name field values in my template.its .giving null value

James

unread,
Nov 7, 2022, 1:21:02 PM11/7/22
to Django users
Hi;

There's a method you're supposed to override in your views (inherit from Views) to do what you want, it's called "get_context_data". This method will pump whatever data you send to it into your template tags.
Reply all
Reply to author
Forward
0 new messages