Search code examples
djangodjango-modelsdjango-viewsdjango-templatesdjango-custom-tags

Rendering a custom tag with a foreign key into templates issues


Hi this is the model I am working with

from django.db import models from users.models import CustomUser

class Project(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False)
    name = models.CharField(max_length=20, editable=False)
    total = models.DecimalField(max_digits=6, decimal_places=2, editable=False)
    created = models.DateTimeField(auto_now_add=True, editable=False, null=False, blank=False)
        
    def __str__(self):
        return self.name

The class is populated by an HTML form using this view:

def homepage(request):
if request.method == "POST":
    project = Project()
    name = request.POST.get('name')
    total = request.POST.get('total')
    created = datetime.datetime.now()
    user = request.user
    project.user = user
    project.name = name
    project.total = total
    project.created = created
    project.save()
    
    #return HttpResponse(reverse("homepage.views.homepage"))
    return render(request, 'homepage.html')
else:

    return render(request, 'homepage.html')

and so I have added a custom tag into my app which is a function

@register.filter
def monthlyTotal(user):
    this_month = now().month
    return Project.objects.filter(
        created__month=this_month,
        user=user
        ).aggregate(
        sum_total=Sum('total')
        )['sum_total']

I call the tag like this in template

 <p>Total monthly sales = {{ user.username|monthlyTotal }}</p>

however I get an error saying Field ID expected a number but got 'grandmaster' which is the name of my test user who has multiple Project objects.. if I switch to user.id I get no error but it displays None which makes sense because when I look at my project section in admin the field user is populated by the username not the id so there would be no project where user=id


Solution

  • You need to use the user, not the username, so:

    <p>Total monthly sales = {{ user|monthlyTotal }}</p>