Home > OS >  Django cannot display model fields to template
Django cannot display model fields to template

Time:12-03

I have a model from a package I would like to retreive fields from for the user to my template but am struggling to get this to work as I have done with user model previously:

models

class DeviceManager(models.Manager):

    def devices_for_user(self, user, confirmed=None):

        devices = self.model.objects.filter(user=user)
        if confirmed is not None:
            devices = devices.filter(confirmed=bool(confirmed))

        return devices


class Device(models.Model):

    user = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), help_text="The user that this device belongs to.", on_delete=models.CASCADE)
    name = models.CharField(max_length=64, help_text="The human-readable name of this device.")
    confirmed = models.BooleanField(default=True, help_text="Is this device ready for use?")

    objects = DeviceManager()

    class Meta:
        abstract = True

    def __str__(self):
        try:
            user = self.user
        except ObjectDoesNotExist:
            user = None

        return "{0} ({1})".format(self.name, user)

view

from django_otp.models import Device

def account(request):

    user = request.user

    device = Device.objects.all()

    context = {"user": user, "device": device}

    return render(request, 'account.html',context)

template

{{ device.name }}
{{ device.confirmed}}

I am getting the folowing error:

AttributeError: Manager isn't available; Device is abstract

I have also tried to change

device = Device.objects.all()

# To

device = DeviceManager.objects.all() 

But the produces the following error:

AttributeError: type object 'DeviceManager' has no attribute 'objects'

Help is much apprecaietd in displaying the content from model to my template. Thanks

CodePudding user response:

You can’t actually query abstract models like this. I’d suggest looking at Multi-Table Inheritance

CodePudding user response:

Device.objects.all() will return a queryset of devices, so you may want to rename the variable like devices = Device.objects.all().

In your template you can access name and confirmed attributes per instance in the list like {{ device.0.name }}, {{ device.1.name }}. More likely you'll want a to use a loop

{% for device in devices %}
    {{ device.name }}
{% endfor %}

To use your model manager try devices = Device.objects.devices_for_user(user)

  • Related