python - 具有自定义模板的 Django formtools

标签 python django django-formwizard

我有以下自定义向导

<div class="container">
    <div id="smartwizard">
        <ul>
            <li><a href="#step-1">Engagement Setup<br /><small>Basic info</small></a></li>
            <li><a href="#step-2">File Upload<br /><small>Upload files</small></a></li>
            <li><a href="#step-3">Business Rules<br /><small>rules</small></a></li>
            <li><a href="#step-4">Documentation<br /><small>documentation</small></a></li>
        </ul>
        <div>
            <div id="step-1" class="">
                <div id="form-step-0" role="form" data-toggle="validator">
                    <div class="form-group">
                        <label for="text">Code <span class="tx-danger">*</span></label>
                        <input type="text" class="form-control" name="code" id="code" placeholder="Write your code" required>
                        <div class="help-block with-errors"></div>
                    </div>
                </div>
                <hr />
            </div>
....
        </div>
    </div>
    <br />
</div>

我已经设置了 django 表单

class PageOne(forms.Form):
    ibs_code = forms.CharField(max_length=100)
    engagement_name  = forms.CharField(max_length=100)
    engagement_manager = forms.CharField(max_length=100)
    engagement_partner = forms.CharField(max_length=100)
    solution =  forms.CharField(label='What solution would you like to use?', widget=forms.Select(choices=FRUIT_CHOICES))

当然还有观点..

class TestWizard(SessionWizardView):
    file_storage = FileSystemStorage(
        location=os.path.join(settings.MEDIA_ROOT, 'temp_uploads'))


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.is_done = False

    def get_template_names(self):
        if self.is_done:
            # return [self.templates['done']]
            return [TEMPLATES['done']]
        else:
            return [TEMPLATES[self.steps.current]]
     .....
     ......

现在我想在表单中使用自定义模板。意思是,我想用 form-group 等以 html/style 的方式生成表单字段。我怎样才能实现这个目标?

我尝试了 documentation但它们不是自定义模板的任何来源

更新#1:仅做这样的事情是不够的

 <div id="form-step-0" role="form">
     <div class="form-group">
        {% if wizard.form.forms %}
            {{wizard.form.management_form }}
            {% for form in wizard.form.forms %}
                {{form}}
            {% endfor %}
        {% else %}
            {{ wizard.form }}
        {% endif %}
     </div>
 </div>

enter image description here

我需要它看起来就像我放在一起的 html

enter image description here

最佳答案

首先,您可以指定用于表单字段的,例如:

class PageOne(forms.Form):
    ibs_code = forms.CharField(
        max_length=100, 
        widget=forms.TextInput(
            attrs={'class' : 'YourClassName'}
        )
    )

其次,您可以根据需要将各个字段放入模板中

<div class="container">
    <div id="smartwizard">
        <ul>
            <li><a href="#step-1">Engagement Setup<br /><small>Basic info</small></a></li>
            <li><a href="#step-2">File Upload<br /><small>Upload files</small></a></li>
            <li><a href="#step-3">Business Rules<br /><small>rules</small></a></li>
            <li><a href="#step-4">Documentation<br /><small>documentation</small></a></li>
        </ul>
        <form>
            {{ wizard.form.management_form }}
            {% csrf_token %}

        <div>
            <div id="step-1" class="">
                <div id="form-step-0" role="form" data-toggle="validator">
                    <div class="form-group">
                        <label for="text">Code <span class="tx-danger">*</span></label>
                        {{ form.ibs_code }}
                        {{ form.ibs_code.errors }}
                    </div>
                </div>
                <hr />
            </div>
....

       </div>
       </form>


    </div>
    <br />
</div>

编辑 - 实际实时示例

        <form id="" class="max-width-800px margin-center" action="" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            {{ wizard.management_form }}
            {{ wizard.form.media }}
            <input name="job-is_user" type="checkbox" hidden {% if request.user.is_authenticated %}checked{% endif %}>
            <input name="job-is_company" type="checkbox" hidden {% if request.user.company_user %}checked{% endif %}>
            <div class="form-group">
                <label for="id_job-plan_"PLANS[0].id >Job Listing Type</label>
                {{ wizard.form.plan }}
                <div class="alert alert-primary top-3">Jobs are subscription-based and are active until you've filled the position.  At the end of your recurring billing cycle you will be charged and your listing will be moved back to the top of its category.</div>
            </div>
            <div class="form-group row">
                <div class="col-6">
                    <label for="id_job-title">Job Title</label>
                    {{ wizard.form.title }}
                </div>
                <div class="col-6">
                    <label for="id_job-category">Job Category</label>
                    <span class="form-select">
                        {{ wizard.form.category }}
                    </span>
                </div>
            </div>
            <div class="form-group">
                <label for="">Job Type</label>
                <div class="row">
                    {% for employment in EMPLOYMENTS %}
                    <div class="col-4">
                        <span class="form-radio form-radio-lg">
                            <input type="radio" id="id_job-employment_{{employment.id}}" name="job-employment" value="{{ employment.id }}" required {% if job.employment.id == employment.id or wizard.form.employment.value|add:"0" == employment.pk %}checked{% endif %}>
                            <label for="id_job-employment_{{employment.id}}">{{ employment }}</label>
                        </span>
                    </div>
                    {% endfor %}
                </div>
            </div>
            <div class="form-group row">
                <div class="col-6">
                    <label for="id_job-job_level">Job Level</label>
                    <span class="form-select">
                        {{ wizard.form.job_level }}
                    </span>
                </div>
                <div class="col-6">
                    <label for="id_job-salary_range">Job Compensation</label>
                    <span class="form-select">
                        {{ wizard.form.salary_range }}
                    </span>
                </div>
            </div>
            <div id="job-location-groupX" class="form-group">
                <label for="id_job-office_base">Job Location</label>
                <div class="row">
                    {% for office in OFFICE_BASE %} 
                    <div class="col-6">
                        <span class="form-radio form-radio-lg">
                            <input type="radio" id="id_job-office_base_{{office.id}}" name="job-office_base" value="{{ office.id }}" {% if job.office_base.id == office.id or wizard.form.office_base.value|add:"0" == office.pk %}checked{% endif %}>
                            <label for="id_job-office_base_{{office.id}}">{{ office.name }}</label>
                        </span>
                    </div>
                    {% endfor %}
                </div>
                <div id="new-job-location-details" class="hidden top-1">
                    {{ wizard.form.outside_location }}
                    {{ wizard.form.outside_location.errors }}
                    <ul class="list-unstyled list-increase-spacing">
                        <li>
                            <span class="form-checkbox">
                                {{ wizard.form.relocation_assistance }}
                                <label id="label-id_job-relocation_assistance" for="id_job-relocation_assistance">Relocation assistance provided</label>
                                {{ wizard.form.relocation_assistance.errors }}

                            </span>
                        </li>
                        <li>
                            <span class="form-checkbox">
                                {{ wizard.form.visa_sponsorship }}
                                <label for="id_job-visa_sponsorship">Visa sponsorship provided</label>
                                {{ wizard.form.visa_sponsorship.errors }}
                            </span>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="form-group">
                <label for="id_job-description">Job Description</label>
                <div class="col-12">
                {{ wizard.form.description }}
                {{ wizard.form.description.errors }}
                </div>
            </div>
            <div id="job-how-to-apply-groupX" class="form-group">
                <label>How to Apply to This Job</label>
                <div class="row">               
                    <div class="col-6">
                        <span class="form-radio form-radio-lg">
                            <input type="radio" required id="new-job-apply-us" value="4" name="job-apply_online" {% if job.apply_online == 4 or wizard.form.apply_online.value|add:"0" == 4 %}checked {% endif %}>
                            <label for="new-job-apply-us">Through us <em class="float-right tablet-hide">(recommended)</em></label>
                        </span>
                    </div>
                    <div class="col-6">
                        <span class="form-radio form-radio-lg">
                            <input type="radio" id="new-job-apply-you" name="job-apply_online" value="3" {% if job.apply_online == 3 or wizard.form.apply_online.value|add:"0" == 3 %}checked {% endif %}>
                            <label for="new-job-apply-you">Through you <em class="float-right tablet-hide">(external URL)</em></label>
                        </span>
                    </div>
                </div>
                <div id="new-job-apply-details" class="hidden top-1">
                    {{ wizard.form.apply_url }}
                    {{ wizard.form.howto_apply }}
                </div>
            </div>
            <div id="job-extras" class="form-group">
                <h6>Additional Extras <span class="optional-field">(optional)</span></h6>
                {{ wizard.form.addons }}
            </div>
            <button type="submit" class="btn btn-lg btn-solid-teal">{% if request.user.company_user %}Preview Your Listing{% elif request.user.is_authenticated %}Enter Company Details{% else %}User Details{% endif %} &rarr;</button>
        </form>

表单.py

class JobPostWizardForm1(forms.ModelForm):
    error_css_class = "alert alert-error"
    category = forms.ModelChoiceField(Category.objects.all(), empty_label='Choose one...', required=False)
    job_level = forms.ModelChoiceField(JobLevel.objects.all(), empty_label='Choose one...', required=False)
    salary_range = forms.ModelChoiceField(Salary.objects.active(), empty_label='Choose one...', required=False)
    plan = forms.ModelChoiceField(Plan.objects.all(), empty_label=None, required=True, widget=PlanSelect)
    is_user = forms.BooleanField(required=False)
    is_company = forms.BooleanField(required=False)
    class Meta:
        model = Job
        fields = [
            'plan','title','category','employment','job_level','salary_range','office_base', 'outside_location',
            'relocation_assistance','visa_sponsorship','description','apply_online','howto_apply','addons', 'is_user',
            'is_company', 'apply_url'
            ]

    def __init__(self, is_active= False, edit_mode=False, plan=0, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['plan'].initial = Plan.objects.all()[plan]
        if is_active : self.fields['plan'].widget.attrs['disabled'] = True

        self.fields['description'].required = True
        self.fields['apply_url'].widget.attrs['placeholder'] = 'External URL'
        self.fields['howto_apply'].widget = forms.Textarea()
        self.fields['howto_apply'].widget.attrs['rows']=10
        self.fields['howto_apply'].widget.attrs['placeholder']="Additional instructions..."

        self.fields['relocation_assistance'].widget = AuthenticJobsCheckbox()
        self.fields['visa_sponsorship'].widget = AuthenticJobsCheckbox()

        self.fields['addons'].widget = AddOnCheckboxSelectMultiple()
        self.fields['addons'].queryset = AddOnItem.objects.filter(active=True)
        #if edit_mode : self.fields['addons'].widget.attrs['disabled'] = True
        if is_active : self.fields['addons'].widget.attrs['onclick'] = "return false;"
        self.error_class = DivErrorList

关于python - 具有自定义模板的 Django formtools,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57492004/

相关文章:

python - Django formtools 向导生成空白页(未返回错误)

python - 将 4 个 numpy 数组中的坐标写入文件 Python

javascript - 改变html中id属性的方法

python - Django 。如何编辑并保存 json 文件中的更改?

django - 在 Formwizard 的一步中同时生成表单和表单集

python - 如何使用 ModelForm 和 ModelFormSet

python - 如何将 pandas loc 索引器转换为字符串?

python - 在Shinyproxy中为Dash应用交付静态 Assets 时出错

Python使用Selenium,ValueError : too many values to unpack

django - django widget_tweaks 可以将输入渲染为文本区域框吗?