pytest-django icon indicating copy to clipboard operation
pytest-django copied to clipboard

Not able to reset django form field initial value

Open truthdoug opened this issue 1 year ago • 1 comments

I have a django form with a field defined like this:

    myField = forms.CharField(
        widget=forms.HiddenInput(),
        initial=f"2023-{settings.FIELD_BASE}",
    )

I'm writing a test where I'd like to use @pytest.mark.parametrize to test different values of FIELD_BASE. Something like:

@pytest.mark.parametrize("test_base", ["aa", "bb", "cc"])
def test_bases(self, client, settings, test_base):
    settings.FIELD_BASE = test_base

    response = client.get(reverse(someview))
    assert f'name="myField" value="2023-{test_base}" in response.content

This does not work. My hunch is that it's because initial is set when the module is loaded at the beginning of the test run. So I tried reloading, adding the two lines after the settings update:

    settings.FIELD_BASE = test_base
    import importlib
    importlib.reload('myapp.forms')

Still no luck.

Any thoughts on how to handle this?

truthdoug avatar Mar 10 '23 17:03 truthdoug

My hunch is that it's because initial is set when the module is loaded at the beginning of the test run.

Right.

Any thoughts on how to handle this?

Try using a callable:

    myField = forms.CharField(
        widget=forms.HiddenInput(),
        initial=lambda: f"2023-{settings.FIELD_BASE}",
    )

If this doesn't work, I think mocking myField.initial directly would work.

bluetech avatar Apr 05 '23 07:04 bluetech