pythondjangodjango-modelsdjango-viewsdjango-custom-user

Query Django custom user model with many-to-many field


I'm very new at Django. I have a custom user model:
accounts\models.py:

from django.contrib.auth.models import AbstractUser
from django.db import models
from tradestats.models import Webhook


class CustomUser(AbstractUser):
    webhook = models.ManyToManyField(Webhook, blank=True)

I have a tradestats app with a Webhook model:
tradestats\models.py

from django.db import models


class Webhook(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    name = models.CharField(verbose_name='Webhooks name', max_length=50, null=False, blank=False)
    url = models.URLField(max_length=255, null=False, blank=False, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']

I have a class based View. In this View I like to query the logged in user all Webhooks url field and pass to render() as a context.
tradestats\view.py:

           context = {
                'form': form.cleaned_data,
                'variable': value1,
                'variable2': value2,
            }
            return render(request, template_name='renko/renko_calculate.html', context=context)

How can I query the webhook.urls and pass into context?


Solution

  • Try the following:

    user = CustomUser.objects.get(id=request.user.id)
    context = {
       ...         
       'webhooks': user.webhook
    }
    ...
    

    or just,

    context = {
       ...         
       'webhooks': request.user.webhook.all()
    }
    ...
    

    It's all there in the documentation


    Another way is to pass user data to the template and access it from there.

    user = CustomUser.objects.get(id=request.user.id)
    context = {
       ...         
       'user': user # needs to filter the content
    }
    
    # can use the request.user approach too
    
    return render(request, template_name='renko/renko_calculate.html', context=context)
    

    in template,

    {% for wh in user.webhook.all %}
        {{ wh.id }} 
        {{ wh.name }} 
        {{ wh.url }} 
    {% endfor %} 
    

    Note: I didn't check this but needs to work