Django-可以将脆脆的表格分为两列吗?

时间:2019-04-19 17:41:51

标签: python django django-forms django-templates

我试图将一个松脆的布局表格分为两列,以消除滚动的需要,我试图在form.py中使用formhelper在DIV中放置两个问题,但这并没有改变。有人有什么想法吗?

forms.py

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Field, Row, Submit, Button, Column

class ProfileUpdateForm(forms.ModelForm):
    address = forms.CharField()
    dob = forms.DateField(
        widget=forms.TextInput(
            attrs={'type': 'date'}
        ), label='Date of Birth'
    )
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Div(
                Div(Field('fullname'), css_class='col-md-6',),
                Div(Field('dob'), css_class='col-md-6',),
                css_class='row',
            ),
            Div(
                Div(Field('address'), css_class='col-md-6',),
                Div(Field('city'), css_class='col-md-6',),
                css_class='row',
            ),
            Div(
                Div(Field('country'), css_class='col-md-6',),
                Div(Field('profilephoto'), css_class='col-md-6',),
                css_class='row',
            ),
        )
        super(ProfileUpdateForm, self).__init__(*args, **kwargs)
    class Meta:
        model = Profile
        fields = ['fullname', 'dob', 'address', 'city', 'country', 'profilephoto']
        labels = {
            'fullname': 'Full Name',
            'address': 'Address',
            'city': 'City',
            'country': 'Country',
            'profilephoto': 'Profile Photo',
        }

views.py

@login_required
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)

        if u_form.is_valid and p_form.is_valid:
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been successfully updated!')
            return redirect('profile')
    else:   
        u_form = UserUpdateForm(instance = request.user)
        p_form = ProfileUpdateForm(instance = request.user.profile)

    context = {
        'u_form': u_form,
        'p_form': p_form
    }
    return render(request, 'users/profile.html', context)

profile.html

{% load crispy_forms_tags %}

            <form method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                {{ u_form|crispy }}

                {{ p_form|crispy }}

           </form>

当前状态

Current look of the page

编辑将__init__添加到forms.py

1 个答案:

答案 0 :(得分:2)

实际上,我什至不确定您的帮手是否被接走。基于documentation here,应该在__init__处添加formhelper。如果您在模板中不使用{% crispy your_cool_form_name %},那么您的问题也可能在模板中。

您快到了。您是looking for Field

from crispy_forms.layout import Field

[...]


Div(
    Div(Field('fullname'), css_class='col-md-6',),
    Div(Field('dob'), css_class='col-md-6',),
    css_class='row',
),