Search code examples
djangodjango-modelsdjango-viewsdjango-templatesdjango-users

User groups in Django


I just lost myself a little, and I'm stuck on this one.

I have a model which has a group field :

class CalendarGroups(models.Model):
    GRP_CALS = (
        ('Grp1', 'Grp1'),
        ('Grp2', 'Grp2'),
        ('Test', 'Test'),
    )
    name = models.CharField(max_length=155, choices=GRP_CALS, blank=True, null=True)

    def __str__(self):
        return self.name

    class Meta:
        ...


class CalendarMaster(models.Model):
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    group = models.ForeignKey(CalendarGroups, on_delete=models.CASCADE)
    date_valid = models.DateTimeField(null=True, blank=True)

I just want to check, if the User's group matches the Calendar group - some context will be rendered.

My views :

@login_required(login_url='registration/login')
def add_event(request, pk):
    opp = get_object_or_404(OpportunityList, pk=pk)
    opp_locked = get_object_or_404(Locked, pk=pk)
    user = User.objects.get(username=request.user.username)
    ...
    user_groups = request.user.groups.values_list('name', flat=True)

    events_all = Events.objects.all()
    calendars = Calendar.objects.all()

    form = ...
    if request.method == 'POST':
        form = ...(request.POST or None)

        if form.is_valid():
            event_form = form.save(commit=False)
            event = Events.objects.create(
                event_name=opp_locked.type + '/' + str(opp.oppc_place) + '/' + opp.oppc_client_name,
                event_comment=form.cleaned_data['event_comment'],
                ...
            )
            ...

            event.save()

            messages.success(request, '...' + ...)
            return redirect('...')
    context = {
        'form': form,
        'opp': opp,
        'events': events_all,
        "calendars": calendars,
        "today": datetime.now().date(),
        "user": user,
        "user_groups": user_groups,
    }
    return render(request, '...', context)

I need something like :

{% if user_group == calendar_group %}

But somehow, I cant manage it -.-

PS. User groups are the same as CalendarMaster's


Solution

  • I just added another field which is linking those two tables. Since there wasn't any relation to those two tables, it was impossible to link them by any chance.