Django Update - ModelForm for Dynamic Field

I am trying to update some ModelForm fields, these fields are not fixed. (I only tutorhave one that is autocast in view)

Model:

class Session(models.Model):
  tutor = models.ForeignKey(User)
  start_time = models.DateTimeField()
  end_time = models.DateTimeField()
  status = models.CharField(max_length=1)

the form:

class SessionForm(forms.ModelForm):
  class Meta:
    model = Session
    exclude = ['tutor']

For this session, sometimes I need to update only end_time, and sometimes only start_time, and end_time.

How can I do this in a view?


Edit

I gave examples, but not limited to these examples, the fields that I need to update are not predefined, I need to be able to update any fields

+3
source share
4 answers

- , , . . django.

.. .

  • ,

, :

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!
+8

"" ex:

class SessionForm(forms.ModelForm):
    def clean_end_date(self):
        cd = self.cleaned_data
        if (cd["start_date"] and cd["end_date"]) and cd["end_date"] < cd["start_date"]:
            raise forms.ValidationError("WTF?!")
        if not (cd["start_date"] or cd["end_date"]):
            raise forms.ValidationError("need one date")
        return cd['end_date']

, return.

, .

, GET ,

def my_view(request):
    r_data = request.GET.copy()
    r_data.merge(request.POST)

    data = dict([(key, my_function(key, value)) for key, value in r_data.iteritems() if key in MyForm.fields])
    form = MyForm(data=data)
    [...]

, .

+1

:

class SessionForm(forms.ModelForm):
    class Meta:
        model = Session
        exclude = ['tutor', 'start_time']

    def __init__(self, your_extra_args, *args, **kwargs):
        super(SessionForm, self).__init__(*args, **kwargs)
        if need_end_time_start_time(your_extra_args):
            self.fields['start_time'] = forms.DateTimeField()     

, "your_extra_args" :

session_form = SessionForm('foo')
0

, , , ModelForm, .

, ModelForm, Meta. . , ModelForm, .

With this, you will have two different forms, which depend on the same model, with different default fields.

With smart url and view design, you can use the above idea to serve multiple forms from the same model.

0
source

All Articles