Home > Mobile >  How to set file visibility to other users?
How to set file visibility to other users?

Time:12-10

Hi im trying to make user upload a file, and then choose to which users this file will be visible .How do i set this one to many relation.This is my models.py file:

from django.db import models

from django.contrib.auth.models import User

class UserFile(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    file = models.FileField(upload_to='media/')
    uploaded = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    trash = models.BooleanField(default=False)
    favourite = models.BooleanField(default=False)

    visibilty = models.ManyToManyField(User)

I tried this but it gives me this error message:

managefiles.UserFile.owner: (fields.E304) Reverse accessor 'User.userfile_set' for 'managefiles.UserFile.owner' clashes with reverse accessor for 'managefiles.UserFile.visibility'.
        HINT: Add or change a related_name argument to the definition for 'managefiles.UserFile.owner' or 'managefiles.UserFile.visibility'.
managefiles.UserFile.visibility: (fields.E304) Reverse accessor 'User.userfile_set' for 'managefiles.UserFile.visibility' clashes with reverse accessor for 'managefiles.UserFile.owner'.
        HINT: Add or change a related_name argument to the definition for 'managefiles.UserFile.visibility' or 'managefiles.UserFile.owner'.

CodePudding user response:

You are getting the error because you have two fields, owner and visibility, referencing the same User table. This can be fixed using related_name.

class UserFile(models.Model):
    owner = models.ForeignKey(Users, related_name='creator', on_delete=models.CASCADE)
    visibility = models.ManyToManyField(Users, related_name='permitted', on_delete=models.CASCADE)
    ...
  • Related