防止用户为其他用户创建实例

发布于 2025-02-04 23:39:22 字数 2006 浏览 1 评论 0原文

我有4种型号与外国钥匙相互关联。

class User(models.Model):
    name = models.CharField()

class Business(models.Model):
    name = models.CharField() //business name
    created_by = models.ForeignKey(User,related_name=businesses,on_del=models.CASCADE)

class ProdCategory(models.Model):
    business = models.ForeignKey(Business,related_name=categories,on_del=models.CASCADE)
    name = models.CharField()

class Product(models.Model):
    category = models.ForeignKey(ProdCategory,related_name=products,on_del=models.CASCADE)
    name = models.ForeignKey()
    price = models.DecimalField()

现在,如果我尝试获取当前身份验证的用户的所有产品,我将获得正确的产品列表(来自同一用户> business> prodCategory> product),

但是如果我尝试使用身份验证的用户创建产品,我可以创建提供prodCategory ID的产品(已经由不同用户创建) (业务用户> prodCategory)!= self.request.user

简而言之,我可以为其他用户创建产品。这不是我想要的。 我想防止当前的用户创建产品,如果提供的prodCategory ID为不同的用户。它应该返回错误。用户必须提供由同一用户创建的ProdCategory的ID。

使用Modelialializer的所有字段定义了序列化器类别。

此处是创建和列表产品的视图:

class CategoryItemListCreateView(generics.ListCreateAPIView):
    serializer_class = CategoryItemSerializer

    def get_queryset(self):
        return CategoryItem.objects.filter(category__budget__created_by=self.request.user).order_by('order')
    
    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        item_data = response.data   
        # there will be multiple categories for One business 
        categories = ProdCategory.objects.filter(business__created_by=request.user)
        for c in categories:
            if item_data['category'] == c.id:
                Product.objects.create(name=item_data['name'], category=item_data['category'])
        return response

我用覆盖的创建方法更新了视图。现在,如果我传递其他用户的类别ID,则可以让我为其他用户创建产品。但是,当我通过请求用户类别的类别ID时,会引发错误,说类别字段应该是prodCategory而不是“ 3”的实例。 (3是prodCategory的ID) 但是,如果我通过{“类别”:1}会创建产品。 (1是其他用户创建的ProdCategory的ID),

我感谢任何帮助。

I have 4 models each related to each other with ForeignKey.

class User(models.Model):
    name = models.CharField()

class Business(models.Model):
    name = models.CharField() //business name
    created_by = models.ForeignKey(User,related_name=businesses,on_del=models.CASCADE)

class ProdCategory(models.Model):
    business = models.ForeignKey(Business,related_name=categories,on_del=models.CASCADE)
    name = models.CharField()

class Product(models.Model):
    category = models.ForeignKey(ProdCategory,related_name=products,on_del=models.CASCADE)
    name = models.ForeignKey()
    price = models.DecimalField()

Now If I try to get all the Products of the current authenticated user I get the Correct List of products (that coming from the same User>Business>ProdCategory>Product)

But if I try to create a Product with authenticated user, I can create a Product with providing the id of ProdCategory(already created by different users)
(User of Business>ProdCategory) != self.request.user

In Short I can create product for other users. Which is not what I want.
I want to prevent the current user from creating products if ProdCategory id provided is of different users. It should return error. User must provide the id of ProdCategory that was created by the same user.

Serializer classes are defined with all fields using ModelSerializer.

Here goes the View for creating and listing products:

class CategoryItemListCreateView(generics.ListCreateAPIView):
    serializer_class = CategoryItemSerializer

    def get_queryset(self):
        return CategoryItem.objects.filter(category__budget__created_by=self.request.user).order_by('order')
    
    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        item_data = response.data   
        # there will be multiple categories for One business 
        categories = ProdCategory.objects.filter(business__created_by=request.user)
        for c in categories:
            if item_data['category'] == c.id:
                Product.objects.create(name=item_data['name'], category=item_data['category'])
        return response

I updated the view with overriding the create method. Now it's letting me create Product for other users if I pass category ID of the other users. But when I pass category id of requesting users category it throws error saying category fields should be instance of ProdCategory not "3". (3 is the id of a ProdCategory)
but if I pass {"category": 1} it creates Product. (1 is the id of ProdCategory created by other users)

I would appreciate any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

余罪 2025-02-11 23:39:22

我没有看到您的创建产品侧。所以我只是写逻辑。

prodCategory= ProdCategory.objects.get(id=1)
if prodCategory.business.created_by == request.user:
     #let user to create the product
     Product.objects.create()
else:
    return False

我希望你了解逻辑

I didn't see your create product side. So I just write the logic.

prodCategory= ProdCategory.objects.get(id=1)
if prodCategory.business.created_by == request.user:
     #let user to create the product
     Product.objects.create()
else:
    return False

I hope you understand the logic

温暖的光 2025-02-11 23:39:22

基本上,我想要的是防止用户将产品推向非用户拥有的产品类别。

我刚找到解决方案。
因此,如果其他人遇到同样的问题,我将在此处添加它。

为了防止用户,我添加了产品序列化机中类别的验证。不需要覆盖创建方法。

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'
    
    def validate_category(self, value):
        category_id = value.id
        category = ProdCategory.objects.get(id=category_id)
        user = self.context['request'].user
        if category.business.created_by != user:
            raise serializers.ValidationError("You do not have permission")
        return value

Basically What I wanted is to prevent the user from pushing Product to ProdCategory that is not own by the user.

I just found a solution.
so I'm adding this here in case anybody else come across the same issue.

to prevent the user I added a validation for category in Product serializer. Overriding the create method is not necessary.

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'
    
    def validate_category(self, value):
        category_id = value.id
        category = ProdCategory.objects.get(id=category_id)
        user = self.context['request'].user
        if category.business.created_by != user:
            raise serializers.ValidationError("You do not have permission")
        return value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文