Django将变量传递给form_class

时间:2017-11-16 22:52:36

标签: python django forms

我试图弄清楚如何访问模型中的字段,该模型在表单查询的模型中用作ForeignKey。

每个Room都有一个表单,用户可以从动态可能Layout个对象列表中选择Layout

1-HTML forms/room/update/layouts.html

<form class="layouts__form form-horizontal" action="" method="post" enctype="multipart/form-data">

    <fieldset class="form__options">

        {% csrf_token %}
        {% for field in form.layout %}
            <div class="layouts__layout"> 
                {{ field.tag }}

                {{ field.choice_label }}

                <label for="value_{{ forloop.counter0 }}">
                    <div class="layouts__layout__thumbnail layouts__layout__thumbnail--{{ field.choice_label }}" style="background-image: url('### (I WOULD LIKE TO LOAD 'Layout.thumbnail' HERE) ###');"></div>
                </label>
            </div>
        {% endfor %}
        <div class="form__submit">
            <button type="submit">Submit</button>
        </div>

    </fieldset>

</form>

2 - 这个表单在views.py

中被调用
class RoomLayoutView(UpdateView):
    model = Room
    form_class = RoomLayoutForm
    template_name = 'forms/room/update/layouts.html'

3 - 这是由forms.py

创建的
class RoomLayoutForm(forms.ModelForm):
    layout = forms.ModelChoiceField(
             widget=forms.RadioSelect(attrs={'type': 'radio', 'id': 'value',}),
             queryset=Layout.objects.all(),
             required=False, empty_label=None)

    class Meta:
        model = Room
        fields = ['layout']

4 - 使用Room模型:

class Room(models.Model):
    title = models.CharField(max_length=200, blank=True)
    layout = models.ForeignKey(Layout, related_name='template_selected', blank=True, null=True)

    def __str__(self):
        return self.title

5 - 其中一个Layout模型作为此处定义的ForeignKey:

class Layout(models.Model):
    title = models.CharField(max_length=200)
    ...
    padding_top = models.IntegerField(blank=False, default=0)
    ...
    thumbnail = models.FileField(upload_to='layouts')
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-title',)

    def __str__(self):
        return self.title

我试图弄清楚如何在实际表单中访问Layout模型中的属性。我特别想在顶部的表单中动态加载Layout.thumbnailLayout.padding_top。我尝试了至少8种不同的方法,但却无法找到一种方法来完成这项工作。任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

this answer中所述,您可以在模板中访问与此表单相关联的当前实例:

{{ form.instance }}

因此,要访问链接的thumbnail的{​​{1}}或padding_top属性:

layout