0

I have limited the amount of files a user can upload to my site using a logical query in my upload app's views.py file. Long story short, after the user has uploaded 5 files, they are redirected to a page that says they must become a premium member.

I am now trying to add to that logic by checking if they are in the "Free User" group. If they are not, they should be allowed to upload an unlimited number of files.

So far I have used the admin panel to create two groups. One is "Free User" and one is "Gold User".

I gave both groups add, change, delete, view permissions for my "beatupload" app.

I added this code to my users models.py

# users/models.py
from django.contrib.auth.models import AbstractUser, Group
from django.db import models

class CustomUser(AbstractUser):
    pass
    # add additional fields in here
    group = models.ForeignKey(Group, on_delete=models.CASCADE, default=1)


    def __str__(self):
        return self.email

I see that I have a field in my users_customuser table for group_id, but when I change the group in the admin interface no changes reflect.

When I check the table using select * from auth_group I see that I have id and group name, being Free User and Gold User.

I am trying to use this query in my upload views.py:

class uploadNew(CreateView): # new
    model = beat
    fields = ['title', 'beat']

    success_url = reverse_lazy('uploads')


    #Check number of beats uploaded by user and if exceeds require signup


    def get_template_names(self):
        if (beat.objects.filter(producer=self.request.user).count() <= 4 and user.groups.filter(name='Free User').exists()):
            return ['uploadNew.html',]
        else:
            return ['becomeMember.html',]

    # END CHECK #
    def form_valid(self, form):
        form.instance.producer = self.request.user
        return super(uploadNew, self).form_valid(form)

So somehow I am not linking my custom user to the group correctly, and there is no checking what group the user is in to either allow unlimited uploads or require becoming a Gold User.

Please let me know if you need to see more code, and also explain for a beginner if possible, noting what areas I may be weak in and need to read more of in Django's documentation. I am on 2.2.2 by the way.

  • Not sure If I understand your question, but to check if a user is in a group, what I have in my code is `request.user.groups.filter(name="group_name_here")` it returns true or false. I also have done like you and created the groups in the Admin Panel. – RonanFelipe Jul 11 '19 at 02:36
  • To add a user in a group in code you could check [this one here](https://stackoverflow.com/questions/6288661/adding-a-user-to-a-group-in-django)!, [or maybe this one](https://stackoverflow.com/questions/40639319/user-groups-addgroup-or-group-user-set-adduser-which-is-better-and-why-or)!. – RonanFelipe Jul 11 '19 at 02:39
  • @Zoro-Zen, is that first link referencing using the shell? I can add users to groups in the admin panel, but when I look at the table of users there is no link between the user and the group. – Alexander Gray Jul 11 '19 at 02:49
  • I just checked my database, and the linking between user and group is in the table `myappname_myuser_groups`. Also to note, I have used `AbstractBaseUser` in my model myuser, so it might not be the same as your prblem description. – RonanFelipe Jul 11 '19 at 02:58
  • If I connect to postgres I see a link in a table called users_customuser_groups. My app is called users and the model class is CustomUser. I just cant figure out how to query that table!!! Driving me nuts. – Alexander Gray Jul 11 '19 at 03:07
  • Is there any data in that table `users_customuser_groups`? If not, try to add some data there using the same approach in the questions linked in the comment above. – RonanFelipe Jul 11 '19 at 03:13
  • There is data, and it is linking my users to the groups i assign them from the admin panel. But in the shell if I try from users.models import CustomUser_groups (or Groups or Group or any capitalization combo), it tells me cannot import. If I can figure out how to write the query that should be it and I just need to add it in my view. – Alexander Gray Jul 11 '19 at 03:16
  • Ohh good there is data in that table, try to get a user in a variable (`one_user = CustomUser.objects.get(pk=1)`) and do something like `one_user.groups.filter(name="group_name_here")` and see if return something. – RonanFelipe Jul 11 '19 at 03:27
  • @Zoro-Zen Yes, it will return with true or false if I query a group name with .exists() class at the end! So now I need to write into my view a query which says "If the currently logged in user is in group "Free User". I'm trying `if (beat.objects.filter(producer=self.request.user).count() <= 4 and request.user.groups.filter(name="Free User").exists()):` but it will not allow unlimited uploads even when the user is not in Free User group. – Alexander Gray Jul 11 '19 at 03:35
  • Check [permission documentation](https://docs.djangoproject.com/en/2.2/topics/auth/default/#permissions-and-authorization) and try to create your custom permission for this case – RonanFelipe Jul 11 '19 at 03:45
  • 1
    @Zoro-Zen I was editing a wrong copy of views, plus my logic was all jacked up. Changing the code to the following is getting my intended results. THANK YOU! `if (beat.objects.filter(producer=self.request.user).count() == 5 and self.request.user.groups.filter(name="Free User").exists()):` – Alexander Gray Jul 11 '19 at 03:51

1 Answers1

0

After creating the groups in admin panel and verifying that a relationship exists when executing

SELECT * from users_customuser_groups;

I was able to get my intended results with the following code:

if (beat.objects.filter(producer=self.request.user).count() == 5 and self.request.user.groups.filter(name="Free User").exists()):

My full models code is posted below for reference. The app name is 'users'

# users/models.py
from django.contrib.auth.models import AbstractUser, Group
from django.db import models

class CustomUser(AbstractUser):
    pass
    # add additional fields in here
    group = models.ForeignKey(Group, on_delete=models.CASCADE, default=1)


    def __str__(self):
        return self.email



VIEWS:

#beatupload/views.py
from django.shortcuts import render
from django.views.generic import ListView, CreateView
from django.urls import reverse_lazy

from .forms import beatUploadForm #new
from .models import beat


# Create your views here.
class UploadView(ListView):
    model = beat
    template_name = 'uploads.html'
    def get_queryset(self):
        return beat.objects.filter(producer=self.request.user)

class uploadNew(CreateView): # new
    model = beat
    fields = ['title', 'beat']

    success_url = reverse_lazy('uploads')
    #Check number of beats uploaded by user and if exceeds amount require signup
    #To render sign up template if true and proceed to upload if false

    def get_template_names(self):
        if (beat.objects.filter(producer=self.request.user).count() == 5 and self.request.user.groups.filter(name="Free User").exists()):
            return ['becomeMember.html',]
        else:
            return ['uploadNew.html',]

    # END CHECK #
    def form_valid(self, form):
        form.instance.producer = self.request.user
        return super(uploadNew, self).form_valid(form)