Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - ModelForm Dynamic field update

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)

like image 776
Pierre de LESPINAY Avatar asked Dec 20 '22 23:12

Pierre de LESPINAY


1 Answers

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.

  • You want to be able to update a model using a form
  • You want to selectively specify which fields are to be updated at run-time

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!
like image 82
Josh Smeaton Avatar answered Dec 28 '22 08:12

Josh Smeaton