简体   繁体   中英

Django forms how to get cleaned_data from fields

Im creating simple dynamic form fields that user can add their form fields and all fields are related to category model. I want that when user select category named car then show them related fields to that car.

my structure:

class Category:
    name = ...


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


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

My problem is how can I generate my form and how to retrieve data from form.cleaned_data and so I can add records to FieldValue model. I created a form and its working fine for rendering using __init__ . And I want to retrieve data from rendered form fields.

my form:

class CategoryFieldsForm(forms.Form):
    def __init__(self, category_id, *args, **kwargs):
        super(CategoryFieldsForm, self).__init__(*args, **kwargs)

        fields = Field.objects.filter(category_id=category_id)

        for i in range(1, len(fields)):
            for field in fields:
                self.fields[field.slug] = forms.CharField()

    def clean(self):
        # how can i validate

    def save(self):
        print(self.cleaned_data)
        # how can i save fields

my view:

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})

When I submit my form CategoryFieldsForm object has no attribute cleaned_data is showing.

You need to instantiate the form with the POST data, then call form.is_valid() before you can access 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()

You can read more about form.is_valid() 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
            ....

Thanks for Daniel Roseman and others. It was more simple error that I was thinking.

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

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

    form = CategoryFieldsForm(category_id)

I was just forget that pass request.POST to my form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM