So, I have a model Project, and it has it's owner (User). Every project has it's own FilePathField, which depends on the owner (different 'match' parameter of FilePathField for different users). But this is not the only model working by this principle.
I can rewrite the constructor (__init__ function) and pass the user there.
Also I can create the Factory to create these models.
What serious people do in this case? (when they must change the model's fields' properties depending on the user)
Model:
class Project(models.Model):
project_file = models.FilePathField(_("Project file"), match='\.prj$', allow_files=True,
allow_folders=False, recursive=True, path=PROJECTS_ROOT, null=False)
name = models.CharField(_("Project name"), max_length=80, null=False)
owner = models.ForeignKey(User, verbose_name=_("Owner"), null=False)
Something like Factory function (just workaround):
def getUserProjectForm(data, user=None):
class ProjectForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
forms.ModelForm.__init__(self, *args, **kwargs)
try:
user_folder = str(user.id)
root_path = join(PROJECTS_ROOT, str(user_folder))
except Exception as e:
user_folder = None
root_path = PROJECTS_ROOT
self.fields['project_file'].path = root_path
self.filter_paths(user_folder)
class Meta:
model = Project
fields = ['name', 'project_file']
def filter_paths(self, user_folder=None):
import re
if user_folder is not None and str(user_folder) != '':
directory = join(PROJECTS_ROOT, str(user_folder))
else:
directory = PROJECTS_ROOT
regexp = re.compile('^%s(.+)$' % directory)
temp_choices = []
db_choices = Project.objects.values_list('project_file', flat=True)
for choice in self.fields['project_file'].choices:
cur_match = regexp.match(choice[0])
if cur_match:
if choice[0] in db_choices:
continue
cur_choice = cur_match.groups()[0]
print "DEBUG"
print choice[0], cur_choice, user_folder
print "DEBUG"
temp_choices.append((choice[0], cur_choice.replace(separator, "", 1)))
self.fields['project_file'].choices = temp_choices
Also. Maybe anyone knows how can I exclude the files which are already in the database? (the last cycle)