I'm trying to update certain fields a ModelForm, these fields are not fixed. (I have only tutor that is autopopulated by the view)
Model:
class Session(models.Model):
  tutor = models.ForeignKey(User)
  start_time = models.DateTimeField()
  end_time = models.DateTimeField()
  status = models.CharField(max_length=1)
Form:
class SessionForm(forms.ModelForm):
  class Meta:
    model = Session
    exclude = ['tutor']
For a given session sometimes I need to update only end_time, sometimes only start_time & end_time.
How can I do that in a view ?
Edit
I have given examples but it's not limited to these examples, the fields I need to update are not predefined, I need to be able to update any field(s)
I've had to do something similar before, and while it isn't exactly pretty, it is quite effective. It involves dynamically creating a type at runtime, and using that type. For some documentation, you can see DynamicModels for django.
Here we go.. your requirements.
So, some code:
def create_form(model, field_names):
    # the inner class is the only useful bit of your ModelForm
    class Meta:
        pass
    setattr(Meta, 'model', model)
    setattr(Meta, 'include', field_names)
    attrs = {'Meta': Meta}
    name = 'DynamicForm'
    baseclasses = (forms.ModelForm,)
    form = type('DynamicForm', baseclasses, attrs)
    return form
def my_awesome_view(request):
    fields = ['start_time', 'end_time']
    form = create_form(Session, fields)
    # work with your form!
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With