9

Django devs, prepare your eye bleach:

(I love that this is possible, but I really don't trust myself to wield the power of making things mutable at will...)

Comments
  • 0
    But why? I don’t really understand why you’d want to add fields to a post call server side 🤔
  • 0
    @620hun the POST -> form -> model -> DB mapping is all done automagically and I need to inject data into the model. To do that, I'd have to override the form processing step.
    But I don't want to deal with that, so I just let the framework handle it and inject the data right into the request.
  • 1
    @franga2000 I know how Django works, hence my confusion. Why do you need to save the PKs when you can access them through the object instance anyway? Even if you insist on saving them, override the save() in the model declaration.
  • 0
    @620hun the model has 3 fields, two of which are foreign keys. The code is from an UpdateView that receives only that one field.
    This caused UpdateView to either try to null the missing fields or complain about their absence.
    I tried filling them in in get_initial(), but that method doesn't have access to the instance, so it doesn't know the values.
    Using this hack, I tricked the UpdateView into thinking the missing fields were there and at the same time made sure that a rogue user couldn't just add their own values to the POST and override the foreign keys.
  • 0
    @franga2000 on your UpdateView

    model = Model
    fields = [‘that_one_field’]

    That’ll tell Django that it should only expect that value.
  • 1
    @620hun that was the first thing I tried and it tried to shove null into the missing fields. What I'd need is the equivalent of the exclude field in ModelForm.
    In fact, that's what I replaced it with when I killed this ungodly mess a good hour ago: a custom form_class with the exclude field and a custom validator to handle fishy POSTs.
  • 2
    @franga2000 weird, I even tried it because I had the same problem. I circumvented it by placing a hidden input with the PK, but looking at yours made me realise how to actually fix it 😛
Add Comment