Kash
Kash

Reputation: 264

Getting date value from django queryset

I have a Models like below

class Member(models.Model):
    memberid = models.AutoField(primary_key=True, editable=False)
    memberdate = models.DateTimeField(default=timezone.now)
    fname = models.CharField(max_length=25)
    mname = models.CharField(max_length=25)
    lname = models.CharField(max_length=25)
    mobile1 = models.CharField(max_length=15)
    email = models.CharField(max_length=150)
    dob = models.DateTimeField(default=timezone.now)

I am fetching data to display in the html template. For the view below is the code

def updateMemberView(request, id):
    searchmem= id
    member = Member.objects.filter(memberid=searchmem).values()
    print(member[0])
    return render(request, 'Member/member_update_form.html', {"member": member})

Now in print(member[0]) I am getting

{'memberid': 13, 'memberdate': datetime.datetime(2020, 4, 11, 0, 0, tzinfo=<UTC>), 'fname': 'Akash', 'mname': 'chimanbhai', 'lname': 'khatri', 'mobile1': '', 'email': '[email protected]', 'dob': datetime.datetime(2020, 4,    3, 0, 0, tzinfo=<UTC>)}

But when I try to print the value of dob in template using member.0.dob it gives me error. Also when I try to execute command

print(member[0].dob)

this also give me error 'dict' object has no attribute 'dob'

So How could I get the dob value in view and also in template.

Upvotes: 1

Views: 92

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477686

This is a dictionary. You access the value corresponding to a key in a dictionary by subscripting:

print(member[0]['dob'])

That being said, using .values(..) [Django-doc] should be used scarcely, especially since you erase the logical layer of the model. For example foreign keys are no longer retrieved lazily, you only have the value of the primary key.

You can simply pass the model object to the template:

from django.shortcuts import get_object_or_404

def update_member_view(request, id):
    member = get_object_or_404(Member, memberid=id)
    return render(request, 'Member/member_update_form.html', {'member': member})

Some common mistakes:

  1. functions are normally written in slug_case, not in PerlCase, or camelCase;
  2. it is better to use get_object_or_404 to return a HTTP 404 exception if the object can not be found; and
  3. as said before, pass the Member object itself, that way you can add extra methods to the model that you can use in the tempate.

Upvotes: 2

Related Questions