Add user to Group after purchase

188 views
Skip to first unread message

Lightning Bit

unread,
Sep 29, 2020, 12:23:19 AM9/29/20
to Django users
Hi All, 

How would one add a user to a certain Backend group in the Django Administration after a user purchases a particular item? I have played around with tons of techniques but nothing is working. 

Thanks!

Derek

unread,
Sep 30, 2020, 2:14:50 AM9/30/20
to Django users
You need to use a "post save" signal; see:

King Niko

unread,
Sep 30, 2020, 7:04:55 PM9/30/20
to django...@googlegroups.com
Thanks Derek!

I tried using the signals but it is not working. This is how my signals and models looks:

Signals.py:
from django.contrib.auth.models import User
from .models import *
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import Group 




@receiver(post_save, sender=User)
def subscription_group(senderinstancecreated, **kwargs):

        if OrderItem.product == 'Subscription_Product':
                Order.complete == True
                group = Group.objects.get(name='subscribees')
                User.groups.add(group)
                print('New Subscribee Added')


Models.py:
from django.db import models
from django.contrib.auth.models import User

# Create your models here.

        
class Customer(models.Model):
    user = models.OneToOneField(User, null=Trueblank=Trueon_delete=models.CASCADE )
    name = models.CharField(max_length=200null=True)
    email = models.CharField(max_length=200null=True)
    phone = models.CharField(max_length=200null=True)
    profile_pic = models.ImageField(default="chicken_suit.gif" ,null=Trueblank=True)
    data_created = models.DateTimeField(auto_now_add=Truenull=True)

    @property
    def picURL(self):
                    try:
                            url = self.profile_pic.url
                    except
                            url= ''
                    return url

    def __str__(self):
        return self.name

class Product(models.Model):
        name = models.CharField(max_length=200)
        price = models.FloatField()
        digital = models.BooleanField(default=Falsenull=Trueblank=True)
        image = models.ImageField(null=Trueblank=True)
        view = models.URLField(default=Falsenull=Trueblank=True)
        

        def __str__(self):
                return self.name
        @property
        def imageURL(self):
                    try:
                            url = self.image.url
                    except
                            url= ''
                    return url

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=Trueblank=True)
    date_ordered = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False)
    transaction_id = models.CharField(max_length=100null=True)

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

    @property 
    def get_cart_total(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.get_total for item in orderitems])
        return total
    
    @property
    def get_cart_items(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.quantity for item in orderitems])
        return total

    @property
    def shipping(self):
        shipping= False
        orderitems = self.orderitem_set.all()
        for i in orderitems:
            if i.product.digital == False:
                    shipping = True
        return shipping

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
    quantity = models.IntegerField(default=0null=Trueblank=True)
    date_added = models.DateTimeField(auto_now_add=True)
    VALUE_ADDED_TAX = 6.0
    tax= VALUE_ADDED_TAX/100
    

    @property
    def get_total(self):
            total = self.product.price * self.quantity + (self.tax * self.product.price)
            return total


When an individual purchases, the signal is not received and that individual is not added to the "subscribees" group. 

Any further suggestions?

Derek

unread,
Oct 1, 2020, 9:36:00 AM10/1/20
to Django users
I am not sure about your details but is my code structure.  Note that the signals are in the same file as the models (may be easier to start there first).

from django.db.models.signals import post_save


class MyModel(Model):
    id = AutoField(primary_key=True)
    # etc.


def MyModel_postsave_handler(sender, **kwargs):
    obj = kwargs['instance']  # object that was saved!
    # add logic  ...


post_save.connect(
    MyModel_postsave_handler,
    sender=MyModel,
    dispatch_uid="mymodel.models") 
    

I hope this simple example can help?  Try to use pdb to see if the postsave_handler function is reached.

Lightning Bit

unread,
Oct 2, 2020, 8:42:52 PM10/2/20
to Django users
I did a bit of testing and I discovered a new method for adding a user to a group after purchase. It is similar to signals, except it strictly uses the views.py:

This current version is bugged (since I am a Django noob), but if I can somehow direct the active authenticated user to the new group through the code below, this issue will finally be resolved: 

def Order_Processor(request):
    
            if request.user.is_authenticated:
                        customer= request.user.customer
                        order,created = Order.objects.get_or_create(customer=customer, complete=False)
                        
                        user = request.user.is_authenticated
                        group = Group.objects.get(name='target_group')
                        user.groups.add(group)
            
            return redirect('home')

The area in red is what really needs some editing. Would you happen to know how to modify this for operationality? 

Thank you!!

Dvs Khamele

unread,
Oct 11, 2020, 1:12:10 PM10/11/20
to django...@googlegroups.com
Hi do you hire contract based python/django freelancer?
 We can help you in this and related tasks at fair prices. Reply or send email to div...@pythonmate.com
Best Regards, 
Divyesh Khamele,
Pythonmate

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ea183d28-fa0f-41ac-acfa-1d49b50a6168n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages