そのため、モデル プロジェクトがあり、その所有者 (ユーザー) がいます。すべてのプロジェクトには、所有者に応じて独自の FilePathField があります (ユーザーごとに FilePathField の「一致」パラメーターが異なります)。しかし、これがこの原則に従って機能する唯一のモデルではありません。
コンストラクター ( __ init __関数) を書き直して、そこにユーザーを渡すことができます。
また、これらのモデルを作成するために Factory を作成することもできます。
この場合、深刻な人々は何をしますか?(ユーザーに応じてモデルのフィールドのプロパティを変更する必要がある場合)
モデル:
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)
ファクトリ関数のようなもの (単なる回避策):
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
また。すでにデータベースにあるファイルを除外する方法を知っている人はいますか? (最後のサイクル)