Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not able to reset django form field initial value #1050

Open
truthdoug opened this issue Mar 10, 2023 · 1 comment
Open

Not able to reset django form field initial value #1050

truthdoug opened this issue Mar 10, 2023 · 1 comment

Comments

@truthdoug
Copy link

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?

@bluetech
Copy link
Member

bluetech commented Apr 5, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants