G
G
gimntut2014-09-04 18:05:54
Django
gimntut, 2014-09-04 18:05:54

How to change the date field value correctly?

There is a dynamically generated model.
It works like this:

# ...
    # model_cls - динамически сгенерированная модель
    class ValidationForm(ModelForm):
        class Meta:
            model = model_cls
            fields = '__all__'
    form = ValidationForm(params)
    if form.is_valid():
        params = form.cleaned_data
    model_cls.objects.create(**params).save()
    # ...

With this approach, the language is taken into account and therefore the date of the form "09/04/2014" is processed without errors.
Now the task arose to save a separate value in a separate model:
function func(model_cls, row_id, field_name, field_value):
    row = model_cls.objects.get(id = row_id)
    row.__setattr__(field_name, field_value)
    row.save()

This approach does not work, because does not take into account the language and requires dates in the format "YYYY-MM-DD"
How to solve this problem in a more beautiful way?
UPD. It would be desirable to do standard validation with transformation, but not for the form, but only for one field.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gimntut, 2014-09-05
@gimntut

Settled on this one:

# ...
    class ValidationForm(ModelForm):
        class Meta:
            model = model_cls
            fields = (field_name, )
    params = {field_name: field_value}
    form = ValidationForm(params)
    if form.is_valid():
        field_value = form.cleaned_data[field_name]
    # ...
    row = model_cls.objects.get(id = row_id)
    if hasattr(row, field_name):
        row.__setattr__(field_name, field_value)
        row.save()
# ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question