R
R
Rrooom2014-08-12 13:06:20
linux
Rrooom, 2014-08-12 13:06:20

How to modify data before validation for m2m?

Django.
Surely this is googled, but I find it difficult to correctly formulate the question. For simplicity, I'll sketch out the code:

class A(models.model):
   name = models.CharField()

class B(models.Model):
   name = models.CharField
   categories = models.ManyToMany(A)

class BForm(ModelForm):
    class Meta:
        model=B

class MyView(CreateView):
    form = BForm
    model = B

More or less like this. The form is sent by ajax. The problem is that the categories value is generated by a js snippet and sent to the server as an array of model A ids. The form validation generally swears that the categories field is not filled in - indeed, it is not in clenead_data, but it is in data. How to keep in shape?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Simkin, 2014-08-21
@sima007

To save the form, you can do this:
Or like this (If the previous one does not work), but this is more a crutch:

def __init__(*args, **kwargs):
    super(BForm, self).__init__(*args, **kwargs)
    self.fields['category'].required = False

Ps: I see that django expects something like this:
------WebKitFormBoundary9Vc3EoEBGNRCydFq
Content-Disposition: form-data; name="user_permissions"

43
------WebKitFormBoundary9Vc3EoEBGNRCydFq
Content-Disposition: form-data; name="user_permissions"

41
------WebKitFormBoundary9Vc3EoEBGNRCydFq
Content-Disposition: form-data; name="user_permissions"

49
------WebKitFormBoundary9Vc3EoEBGNRCydFq
Content-Disposition: form-data; name="user_permissions"

42
------WebKitFormBoundary9Vc3EoEBGNRCydFq
Content-Disposition: form-data; name="user_permissions"

40
------WebKitFormBoundary9Vc3EoEBGNRCydFq
Content-Disposition: form-data; name="user_permissions"

30

Pps: These are things from php, django can't do that:
a[]=1
a[]=2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question