2

I want to process teplates with django. For that i need to use Choicefield and FilePathField.

I don't really know how to combine them. The Choice field in the form works as expected

class TaskBlockForm(forms.ModelForm):
    """ form used for creating a taskblock
        :param forms.ModelForm: superclass of forms.
    """
    users = forms.ModelMultipleChoiceField(queryset=DemoUser.objects.all())

    upload_by_file = forms.BooleanField()
    file = forms.FileField(label=_('Init script'), required=False)

    template = forms.ChoiceField(widget=forms.Select(), choices=[(0, 'WorldDB'), (1, 'ArticleDB'), (2, 'SampleDB')])
    date = forms.DateField(widget=SelectDateWidget(), label=_('maturity date'), initial=timezone.now())

The Model looks like

def generate_templatename(instance, filename):
    """
    helper method to generate path and filename for a template sql file of a taskblock
    :param instance: taskblock instance
    :param filename: filename
    :return: relative url of file path
    """
    url = "template/%s/%s" % (instance.name, filename)
    return url


class TaskBlock(models.Model):
    """
        model of a taskblock
    """
    name = models.CharField(max_length=20)
    description = models.TextField()
    create_stamp = models.DateTimeField(default=timezone.now)
    file = models.FileField(upload_to=generate_filename, blank=True)
    template = models.FilePathField(path=generate_templatename, default='DEFAULT')

    def __str__(self):
        return self.name

(the setting for the file url should be right - i am using the same approach to store files in the /media/documents directory)

How can i combine those two, so that i can choose the model directly? or do i have to set it manually in the view.py later?

Marcel Hinderlich
  • 213
  • 1
  • 3
  • 19

1 Answers1

0

I found the solution. The problem was the pathsetting.

the function:

def generate_templatename(instance, filename):
    """
    helper method to generate path and filename for a template sql file of a taskblock
    :param instance: taskblock instance
    :param filename: filename
    :return: relative url of file path
    """
    url = "template/%s/%s" % (instance.name, filename)
    return url

can not be used. Instead the path has to be set like the following:

template = models.FilePathField(path=settings.MEDIA_ROOT + settings.TEMPLATE_URL,recursive=True)

MEDIA_ROOT is defined in the settings.py and points to the/media directory

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
TEMPLATE_URL = '/templates/'

Now the form can use the model instead of defining a new template-variable

   template = forms.ChoiceField(widget=forms.Select(), choices=[(0, 'WorldDB'), (1, 'ArticleDB'), (2, 'SampleDB')])

is not used anymore, just extend the meta-settings by:

class Meta:
        model = TaskBlock
        # use following model fields
        fields = ('name', 'description', 'template')
Marcel Hinderlich
  • 213
  • 1
  • 3
  • 19