Home > database >  I want a user to only access download url for pdf if the user exists in order table models how can I
I want a user to only access download url for pdf if the user exists in order table models how can I

Time:07-31

Here is my view function where i have tried to excute the functionality

@login_required
def secure_pdf(request,file):
    user = get_object_or_404(User)
    order = Order.objects.filter(user=user).all()
    
    if user in order:
        document = get_object_or_404(Exam,pdf='pdf/' file)
        path,file_name = os.path.split(file)
        response = FileResponse(document.pdf)
        return response
    else:
        return HttpResponse("acess denied")

my order model

class Order(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, related_name='orders', blank=True, null=True, 
    on_delete=models.CASCADE)
    transaction_id = models.IntegerField(blank=True, null=True)
    status = models.CharField(max_length=60, blank=True, null=True)
    tx_ref = models.IntegerField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

CodePudding user response:

Try to read a little bit more about Django: https://docs.djangoproject.com/en/4.0/

at first. If you use authentication from django:

user = request.user

At second. What you mean if user in order. User cannot be in list of orders. user is User model and order is Order model. Something really wrong in your logic.

orders = Order.objects.filter(user=user).all()  # this is list of orders

orders - is already filtered by user list of orders.

if orders.count():
    ...

or

if orders.exists():
    ...

You can use oredrs.get, orders.list, orders.first. But you don't use it anywhere. And all what happens in if clause is not readable. Exam? File? Path? file_name? What you want to do?

  • Related