Django表单如何从字段中获取已清理的数据

2024-09-26 22:13:36 发布

您现在位置:Python中文网/ 问答频道 /正文

Im正在创建简单的动态form fields,用户可以添加他们的表单字段,并且所有字段都与category模型相关。我希望当用户选择名为carcategory,然后向他们显示与该车相关的fields。在

我的结构:

class Category:
    name = ...


class Field:
    label = ...
    category = ForeignKey(Category)


class FieldValue:
    value = ...
    field = ForeignKey(Field)

我的问题是如何生成我的表单以及如何从form.cleaned_data中检索数据,从而可以将记录添加到FieldValue模型中。我创建了一个表单,它可以很好地使用__init__进行渲染。我想从呈现的表单字段中检索数据。在

我的表格:

^{pr2}$

我的观点:

def some_create_view(request, category_id):
    if request.method == 'POST':
        form = CategoryFieldsForm(category_id)
        form.save()

    form = CategoryFieldsForm(category_id)

    return render(request, 'create.html', {'form': form})

当我提交表单时,CategoryFieldsForm对象没有属性cleaned_data显示。在


Tags: 用户模型formid表单fieldfieldsrequest
3条回答

你可以读更多关于表格有效吗()here。在

A Form instance has an is_valid() method, which runs validation routines for all its fields. When this method is called, if all fields contain valid data, it will:

1) return True

2) place the form’s data in its cleaned_data attribute.

def some_create_view(request, category_id):
    if request.method == 'POST':
        form = CategoryFieldsForm(category_id, request.POST)
        if form.valid():                
            # you should be able to access the form cleaned data here
            ....

您需要用POST数据实例化表单,然后调用form.is_valid(),然后才能访问form.cleaned_data。在

def some_create_view(request, category_id):
    if request.method == 'POST':
        form = CategoryFieldsForm(category_id, data=request.POST)
        if form.is_valid():
            form.save()

感谢Daniel Roseman和其他人。我认为这是一个更简单的错误。在

if request.method == 'POST':
        form = CategoryFieldsForm(category_id, request.POST)

        if form.is_valid():
            print(form)
        else:
            print(form.errors)

    form = CategoryFieldsForm(category_id)

我只是忘了把request.POST传给我的表格。在

相关问题 更多 >

    热门问题