Ad

In Django How To Add User To Many-to-many Filed

- 1 answer

I like to add permission to those users who I add to a many-to-many relation. I have a Projekt model where I like to add multiple users like this:

class Projekt(models.Model):

def __str__(self):
    return str(self.projekt)

    projekt = models.TextField(max_length=150)
    company_name = models.ForeignKey('Company', on_delete=models.CASCADE, default=1)
    jogosult_01 = models.ManyToManyField(User)
    date = models.DateField(auto_now_add=True, auto_now=False, blank=True)

I add the users in the Django Admin page with holding down cmd then save and it shows everything is OK.

If try to get the values like this:

{% for u in jogosult %}
    {{ u.jogosult_01 }}
{% endfor %}

it say auth.user none.

views.py

@login_required
def projects(request):

    jogosult = Projekt.objects.filter(jogosult_01_id=request.user).order_by('-date')

     context = {
        'jogosult': jogosult,
     }

     return render(request, 'stressz/projects.html', context)
Ad

Answer

User objects have access to their related Projekt objects:

@login_required
def projects(request):

    jogosult = request.user.projekt_set.all() #<-- HERE!

     context = {
        'jogosult': jogosult,
     }

     return render(request, 'stressz/projects.html', context)

Is full documented at Many-to-many relationships

Ad
source: stackoverflow.com
Ad