Django model objects do not load in Form in testing environment












0















Using Django 2.1.3



Getting a strange error here; I have a form multiplechoicefield that draws its choices from the values existing in a model in the database.



class ChartForm(Form):
P_CHOICES = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p"))

p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1])


I am trying to run tests for a different app in the project. It throws the following error:



  File "/code/pyyc/forms.py", line 31, in ChartForm
p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1])
IndexError: tuple index out of range


I assumed it was just because the model objects weren't loaded. So I added in the fixtures from the VAR app.



And yet, it still throws the error. Presumably, the Form is render before the test database is compiled ... ?



So I am now editing the Form so that P_CHOICES is done manually, but this is obviously not ideal for the test environment.



Anyone ever come across this? Is there a smart hack for this that doesn't involve commenting out lines in the Form every time you want to test?










share|improve this question























  • Can you try printing the output of VAR.objects.all() to know for sure that form is rendering before the db is created.

    – xyres
    Jan 1 at 18:29











  • thx. I did. Returns None

    – Ry John
    Jan 1 at 21:26











  • You should really use a ModelChoiceField with a queryset fur this sort of thing.

    – Daniel Roseman
    Jan 1 at 21:42











  • not sure i understand. all() is a queryset. any queryset will not load appropriately i don't believe.

    – Ry John
    Jan 2 at 0:04
















0















Using Django 2.1.3



Getting a strange error here; I have a form multiplechoicefield that draws its choices from the values existing in a model in the database.



class ChartForm(Form):
P_CHOICES = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p"))

p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1])


I am trying to run tests for a different app in the project. It throws the following error:



  File "/code/pyyc/forms.py", line 31, in ChartForm
p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1])
IndexError: tuple index out of range


I assumed it was just because the model objects weren't loaded. So I added in the fixtures from the VAR app.



And yet, it still throws the error. Presumably, the Form is render before the test database is compiled ... ?



So I am now editing the Form so that P_CHOICES is done manually, but this is obviously not ideal for the test environment.



Anyone ever come across this? Is there a smart hack for this that doesn't involve commenting out lines in the Form every time you want to test?










share|improve this question























  • Can you try printing the output of VAR.objects.all() to know for sure that form is rendering before the db is created.

    – xyres
    Jan 1 at 18:29











  • thx. I did. Returns None

    – Ry John
    Jan 1 at 21:26











  • You should really use a ModelChoiceField with a queryset fur this sort of thing.

    – Daniel Roseman
    Jan 1 at 21:42











  • not sure i understand. all() is a queryset. any queryset will not load appropriately i don't believe.

    – Ry John
    Jan 2 at 0:04














0












0








0








Using Django 2.1.3



Getting a strange error here; I have a form multiplechoicefield that draws its choices from the values existing in a model in the database.



class ChartForm(Form):
P_CHOICES = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p"))

p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1])


I am trying to run tests for a different app in the project. It throws the following error:



  File "/code/pyyc/forms.py", line 31, in ChartForm
p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1])
IndexError: tuple index out of range


I assumed it was just because the model objects weren't loaded. So I added in the fixtures from the VAR app.



And yet, it still throws the error. Presumably, the Form is render before the test database is compiled ... ?



So I am now editing the Form so that P_CHOICES is done manually, but this is obviously not ideal for the test environment.



Anyone ever come across this? Is there a smart hack for this that doesn't involve commenting out lines in the Form every time you want to test?










share|improve this question














Using Django 2.1.3



Getting a strange error here; I have a form multiplechoicefield that draws its choices from the values existing in a model in the database.



class ChartForm(Form):
P_CHOICES = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p"))

p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1])


I am trying to run tests for a different app in the project. It throws the following error:



  File "/code/pyyc/forms.py", line 31, in ChartForm
p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1])
IndexError: tuple index out of range


I assumed it was just because the model objects weren't loaded. So I added in the fixtures from the VAR app.



And yet, it still throws the error. Presumably, the Form is render before the test database is compiled ... ?



So I am now editing the Form so that P_CHOICES is done manually, but this is obviously not ideal for the test environment.



Anyone ever come across this? Is there a smart hack for this that doesn't involve commenting out lines in the Form every time you want to test?







django testing






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 1 at 17:22









Ry JohnRy John

190113




190113













  • Can you try printing the output of VAR.objects.all() to know for sure that form is rendering before the db is created.

    – xyres
    Jan 1 at 18:29











  • thx. I did. Returns None

    – Ry John
    Jan 1 at 21:26











  • You should really use a ModelChoiceField with a queryset fur this sort of thing.

    – Daniel Roseman
    Jan 1 at 21:42











  • not sure i understand. all() is a queryset. any queryset will not load appropriately i don't believe.

    – Ry John
    Jan 2 at 0:04



















  • Can you try printing the output of VAR.objects.all() to know for sure that form is rendering before the db is created.

    – xyres
    Jan 1 at 18:29











  • thx. I did. Returns None

    – Ry John
    Jan 1 at 21:26











  • You should really use a ModelChoiceField with a queryset fur this sort of thing.

    – Daniel Roseman
    Jan 1 at 21:42











  • not sure i understand. all() is a queryset. any queryset will not load appropriately i don't believe.

    – Ry John
    Jan 2 at 0:04

















Can you try printing the output of VAR.objects.all() to know for sure that form is rendering before the db is created.

– xyres
Jan 1 at 18:29





Can you try printing the output of VAR.objects.all() to know for sure that form is rendering before the db is created.

– xyres
Jan 1 at 18:29













thx. I did. Returns None

– Ry John
Jan 1 at 21:26





thx. I did. Returns None

– Ry John
Jan 1 at 21:26













You should really use a ModelChoiceField with a queryset fur this sort of thing.

– Daniel Roseman
Jan 1 at 21:42





You should really use a ModelChoiceField with a queryset fur this sort of thing.

– Daniel Roseman
Jan 1 at 21:42













not sure i understand. all() is a queryset. any queryset will not load appropriately i don't believe.

– Ry John
Jan 2 at 0:04





not sure i understand. all() is a queryset. any queryset will not load appropriately i don't believe.

– Ry John
Jan 2 at 0:04












1 Answer
1






active

oldest

votes


















1














Your presumption I think is correct. The class level attribute P_CHOICES is created when Python first loads the ChartForm class, before the test has actually started running. The fixtures are installed later as part of the test's setUpClass() (called by the test framework) but by that point P_CHOICES has already been defined and is empty.



You could try creating the MultipleChoiceField without its choices and initial attributes, and then set those in the form's __init__ when the data is available. For example:



class ChartForm(Form):
p = MultipleChoiceField(widget=CheckboxSelectMultiple)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
p_choices = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p"))
# Now we have the data we can set the attributes
self.fields['p'].choices = p_choices
self.fields['p'].initial = p_choices[0][1]





share|improve this answer
























  • great idea thanks

    – Ry John
    Jan 1 at 21:27











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53997462%2fdjango-model-objects-do-not-load-in-form-in-testing-environment%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














Your presumption I think is correct. The class level attribute P_CHOICES is created when Python first loads the ChartForm class, before the test has actually started running. The fixtures are installed later as part of the test's setUpClass() (called by the test framework) but by that point P_CHOICES has already been defined and is empty.



You could try creating the MultipleChoiceField without its choices and initial attributes, and then set those in the form's __init__ when the data is available. For example:



class ChartForm(Form):
p = MultipleChoiceField(widget=CheckboxSelectMultiple)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
p_choices = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p"))
# Now we have the data we can set the attributes
self.fields['p'].choices = p_choices
self.fields['p'].initial = p_choices[0][1]





share|improve this answer
























  • great idea thanks

    – Ry John
    Jan 1 at 21:27
















1














Your presumption I think is correct. The class level attribute P_CHOICES is created when Python first loads the ChartForm class, before the test has actually started running. The fixtures are installed later as part of the test's setUpClass() (called by the test framework) but by that point P_CHOICES has already been defined and is empty.



You could try creating the MultipleChoiceField without its choices and initial attributes, and then set those in the form's __init__ when the data is available. For example:



class ChartForm(Form):
p = MultipleChoiceField(widget=CheckboxSelectMultiple)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
p_choices = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p"))
# Now we have the data we can set the attributes
self.fields['p'].choices = p_choices
self.fields['p'].initial = p_choices[0][1]





share|improve this answer
























  • great idea thanks

    – Ry John
    Jan 1 at 21:27














1












1








1







Your presumption I think is correct. The class level attribute P_CHOICES is created when Python first loads the ChartForm class, before the test has actually started running. The fixtures are installed later as part of the test's setUpClass() (called by the test framework) but by that point P_CHOICES has already been defined and is empty.



You could try creating the MultipleChoiceField without its choices and initial attributes, and then set those in the form's __init__ when the data is available. For example:



class ChartForm(Form):
p = MultipleChoiceField(widget=CheckboxSelectMultiple)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
p_choices = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p"))
# Now we have the data we can set the attributes
self.fields['p'].choices = p_choices
self.fields['p'].initial = p_choices[0][1]





share|improve this answer













Your presumption I think is correct. The class level attribute P_CHOICES is created when Python first loads the ChartForm class, before the test has actually started running. The fixtures are installed later as part of the test's setUpClass() (called by the test framework) but by that point P_CHOICES has already been defined and is empty.



You could try creating the MultipleChoiceField without its choices and initial attributes, and then set those in the form's __init__ when the data is available. For example:



class ChartForm(Form):
p = MultipleChoiceField(widget=CheckboxSelectMultiple)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
p_choices = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p"))
# Now we have the data we can set the attributes
self.fields['p'].choices = p_choices
self.fields['p'].initial = p_choices[0][1]






share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 1 at 20:52









Will KeelingWill Keeling

12k22635




12k22635













  • great idea thanks

    – Ry John
    Jan 1 at 21:27



















  • great idea thanks

    – Ry John
    Jan 1 at 21:27

















great idea thanks

– Ry John
Jan 1 at 21:27





great idea thanks

– Ry John
Jan 1 at 21:27




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53997462%2fdjango-model-objects-do-not-load-in-form-in-testing-environment%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Mossoró

Error while reading .h5 file using the rhdf5 package in R

Pushsharp Apns notification error: 'InvalidToken'