Setting queryset within forms.ModelChoiceField()










0















The queryset for the 'jurisdiction' field is set below in the initialization. The queryset is dependent on the id that is passed in, which comes from a specific link that a user clicks. As a result, I can't define a singular queryset within the forms.ModelChoiceField(), but it seems that django requires me to do this.



class TaxForm (forms.ModelForm): #Will be used for state tax and other taxes

jurisdiction = forms.ModelChoiceField(queryset=?????)

class Meta:
model = Tax
exclude = ('user', 'taxtype',)

def __init__(self, *args, **kwargs):

self.taxtype = kwargs.pop('taxtype',None)
super(TaxForm, self).__init__(*args, **kwargs)

if int(self.taxtype) == 1:
self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.all()]
elif int(self.taxtype) == 2:
self.fields['jurisdiction'].choices = [(t.id, t) for t in Country.objects.all()]
else:
self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.none()]


How can I indicate that I want the jurisdiction field to be a dropdown, but not specify one queryset within the forms.ModelChoiceField()? Alternatively, how can I make the queryset that is referenced in forms.ModelChoiceField() refer to the queryset that I initialize based on the taxtype?



Thanks!



Here is my tax model



class Tax(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
jurisdiction = models.CharField(max_length=120, null=True, blank=True)
name = models.CharField(max_length=200)
rate = models.DecimalField(max_digits=10, decimal_places=2)
basis = models.CharField(max_length=120, null=True, blank=True)
regnumber = models.CharField(max_length=200, null=True, blank=True) #tax number that will appear on customer invoice
taxtype = models.IntegerField(blank=True, null=True) # 0 is other, 1 is state, 2 is federal

def __str__(self):
return ' - '.format(self.user, self.name)









share|improve this question
























  • just try following way forms.ModelChoiceField(queryset=None) and self.fields['jurisdiction'].queryset =State.objects.all()

    – Pavan Kumar T S
    Nov 13 '18 at 8:19











  • This can't work, a ModelChoiceField needs to have a specific model as its target, because it represents an underlying ForeignKey. What does your model field look like? But in your code, since you're setting choices anyway, there doesn't seem to be any good reason to use a ModelChoiceField, you should use a simple ChoiceField.

    – Daniel Roseman
    Nov 13 '18 at 8:42











  • I've updated my question to include my Tax model within models.py. Thanks again Daniel! Let me know if you still think I should use a ChoiceField.

    – Jason Howard
    Nov 13 '18 at 8:52















0















The queryset for the 'jurisdiction' field is set below in the initialization. The queryset is dependent on the id that is passed in, which comes from a specific link that a user clicks. As a result, I can't define a singular queryset within the forms.ModelChoiceField(), but it seems that django requires me to do this.



class TaxForm (forms.ModelForm): #Will be used for state tax and other taxes

jurisdiction = forms.ModelChoiceField(queryset=?????)

class Meta:
model = Tax
exclude = ('user', 'taxtype',)

def __init__(self, *args, **kwargs):

self.taxtype = kwargs.pop('taxtype',None)
super(TaxForm, self).__init__(*args, **kwargs)

if int(self.taxtype) == 1:
self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.all()]
elif int(self.taxtype) == 2:
self.fields['jurisdiction'].choices = [(t.id, t) for t in Country.objects.all()]
else:
self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.none()]


How can I indicate that I want the jurisdiction field to be a dropdown, but not specify one queryset within the forms.ModelChoiceField()? Alternatively, how can I make the queryset that is referenced in forms.ModelChoiceField() refer to the queryset that I initialize based on the taxtype?



Thanks!



Here is my tax model



class Tax(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
jurisdiction = models.CharField(max_length=120, null=True, blank=True)
name = models.CharField(max_length=200)
rate = models.DecimalField(max_digits=10, decimal_places=2)
basis = models.CharField(max_length=120, null=True, blank=True)
regnumber = models.CharField(max_length=200, null=True, blank=True) #tax number that will appear on customer invoice
taxtype = models.IntegerField(blank=True, null=True) # 0 is other, 1 is state, 2 is federal

def __str__(self):
return ' - '.format(self.user, self.name)









share|improve this question
























  • just try following way forms.ModelChoiceField(queryset=None) and self.fields['jurisdiction'].queryset =State.objects.all()

    – Pavan Kumar T S
    Nov 13 '18 at 8:19











  • This can't work, a ModelChoiceField needs to have a specific model as its target, because it represents an underlying ForeignKey. What does your model field look like? But in your code, since you're setting choices anyway, there doesn't seem to be any good reason to use a ModelChoiceField, you should use a simple ChoiceField.

    – Daniel Roseman
    Nov 13 '18 at 8:42











  • I've updated my question to include my Tax model within models.py. Thanks again Daniel! Let me know if you still think I should use a ChoiceField.

    – Jason Howard
    Nov 13 '18 at 8:52













0












0








0








The queryset for the 'jurisdiction' field is set below in the initialization. The queryset is dependent on the id that is passed in, which comes from a specific link that a user clicks. As a result, I can't define a singular queryset within the forms.ModelChoiceField(), but it seems that django requires me to do this.



class TaxForm (forms.ModelForm): #Will be used for state tax and other taxes

jurisdiction = forms.ModelChoiceField(queryset=?????)

class Meta:
model = Tax
exclude = ('user', 'taxtype',)

def __init__(self, *args, **kwargs):

self.taxtype = kwargs.pop('taxtype',None)
super(TaxForm, self).__init__(*args, **kwargs)

if int(self.taxtype) == 1:
self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.all()]
elif int(self.taxtype) == 2:
self.fields['jurisdiction'].choices = [(t.id, t) for t in Country.objects.all()]
else:
self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.none()]


How can I indicate that I want the jurisdiction field to be a dropdown, but not specify one queryset within the forms.ModelChoiceField()? Alternatively, how can I make the queryset that is referenced in forms.ModelChoiceField() refer to the queryset that I initialize based on the taxtype?



Thanks!



Here is my tax model



class Tax(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
jurisdiction = models.CharField(max_length=120, null=True, blank=True)
name = models.CharField(max_length=200)
rate = models.DecimalField(max_digits=10, decimal_places=2)
basis = models.CharField(max_length=120, null=True, blank=True)
regnumber = models.CharField(max_length=200, null=True, blank=True) #tax number that will appear on customer invoice
taxtype = models.IntegerField(blank=True, null=True) # 0 is other, 1 is state, 2 is federal

def __str__(self):
return ' - '.format(self.user, self.name)









share|improve this question
















The queryset for the 'jurisdiction' field is set below in the initialization. The queryset is dependent on the id that is passed in, which comes from a specific link that a user clicks. As a result, I can't define a singular queryset within the forms.ModelChoiceField(), but it seems that django requires me to do this.



class TaxForm (forms.ModelForm): #Will be used for state tax and other taxes

jurisdiction = forms.ModelChoiceField(queryset=?????)

class Meta:
model = Tax
exclude = ('user', 'taxtype',)

def __init__(self, *args, **kwargs):

self.taxtype = kwargs.pop('taxtype',None)
super(TaxForm, self).__init__(*args, **kwargs)

if int(self.taxtype) == 1:
self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.all()]
elif int(self.taxtype) == 2:
self.fields['jurisdiction'].choices = [(t.id, t) for t in Country.objects.all()]
else:
self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.none()]


How can I indicate that I want the jurisdiction field to be a dropdown, but not specify one queryset within the forms.ModelChoiceField()? Alternatively, how can I make the queryset that is referenced in forms.ModelChoiceField() refer to the queryset that I initialize based on the taxtype?



Thanks!



Here is my tax model



class Tax(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
jurisdiction = models.CharField(max_length=120, null=True, blank=True)
name = models.CharField(max_length=200)
rate = models.DecimalField(max_digits=10, decimal_places=2)
basis = models.CharField(max_length=120, null=True, blank=True)
regnumber = models.CharField(max_length=200, null=True, blank=True) #tax number that will appear on customer invoice
taxtype = models.IntegerField(blank=True, null=True) # 0 is other, 1 is state, 2 is federal

def __str__(self):
return ' - '.format(self.user, self.name)






django django-forms






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 8:51







Jason Howard

















asked Nov 13 '18 at 8:06









Jason HowardJason Howard

318112




318112












  • just try following way forms.ModelChoiceField(queryset=None) and self.fields['jurisdiction'].queryset =State.objects.all()

    – Pavan Kumar T S
    Nov 13 '18 at 8:19











  • This can't work, a ModelChoiceField needs to have a specific model as its target, because it represents an underlying ForeignKey. What does your model field look like? But in your code, since you're setting choices anyway, there doesn't seem to be any good reason to use a ModelChoiceField, you should use a simple ChoiceField.

    – Daniel Roseman
    Nov 13 '18 at 8:42











  • I've updated my question to include my Tax model within models.py. Thanks again Daniel! Let me know if you still think I should use a ChoiceField.

    – Jason Howard
    Nov 13 '18 at 8:52

















  • just try following way forms.ModelChoiceField(queryset=None) and self.fields['jurisdiction'].queryset =State.objects.all()

    – Pavan Kumar T S
    Nov 13 '18 at 8:19











  • This can't work, a ModelChoiceField needs to have a specific model as its target, because it represents an underlying ForeignKey. What does your model field look like? But in your code, since you're setting choices anyway, there doesn't seem to be any good reason to use a ModelChoiceField, you should use a simple ChoiceField.

    – Daniel Roseman
    Nov 13 '18 at 8:42











  • I've updated my question to include my Tax model within models.py. Thanks again Daniel! Let me know if you still think I should use a ChoiceField.

    – Jason Howard
    Nov 13 '18 at 8:52
















just try following way forms.ModelChoiceField(queryset=None) and self.fields['jurisdiction'].queryset =State.objects.all()

– Pavan Kumar T S
Nov 13 '18 at 8:19





just try following way forms.ModelChoiceField(queryset=None) and self.fields['jurisdiction'].queryset =State.objects.all()

– Pavan Kumar T S
Nov 13 '18 at 8:19













This can't work, a ModelChoiceField needs to have a specific model as its target, because it represents an underlying ForeignKey. What does your model field look like? But in your code, since you're setting choices anyway, there doesn't seem to be any good reason to use a ModelChoiceField, you should use a simple ChoiceField.

– Daniel Roseman
Nov 13 '18 at 8:42





This can't work, a ModelChoiceField needs to have a specific model as its target, because it represents an underlying ForeignKey. What does your model field look like? But in your code, since you're setting choices anyway, there doesn't seem to be any good reason to use a ModelChoiceField, you should use a simple ChoiceField.

– Daniel Roseman
Nov 13 '18 at 8:42













I've updated my question to include my Tax model within models.py. Thanks again Daniel! Let me know if you still think I should use a ChoiceField.

– Jason Howard
Nov 13 '18 at 8:52





I've updated my question to include my Tax model within models.py. Thanks again Daniel! Let me know if you still think I should use a ChoiceField.

– Jason Howard
Nov 13 '18 at 8:52












1 Answer
1






active

oldest

votes


















0














As I mentioned, ModelChoiceField is not the right thing to do here. That's for allowing the user to choose from related items from a single model that will be saved into a ForeignKey. You don't have a ForeignKey, and what's more you're setting the choices attribute in your init rather than queryset. You should make it a plain ChoiceField with an empty choices parameter:



jurisdiction = forms.ChoiceField(choices=())


(For the sake of completeness: if you did need to use ModelChoiceField you can put anything you like into the queryset parameter when you're overwriting it in __init__, because it will never be evaluated. But managers have a none method which returns an empty queryset, so you could do queryset=State.objects.none().)






share|improve this answer























  • Cool, thanks Daniel. I'll make these changes tonight and let you know if I have any issues. You should have a page where people can donate money to you for your excellent help. I'd make a donation :) Thanks again for all of your help!

    – Jason Howard
    Nov 14 '18 at 0:28










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%2f53276429%2fsetting-queryset-within-forms-modelchoicefield%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









0














As I mentioned, ModelChoiceField is not the right thing to do here. That's for allowing the user to choose from related items from a single model that will be saved into a ForeignKey. You don't have a ForeignKey, and what's more you're setting the choices attribute in your init rather than queryset. You should make it a plain ChoiceField with an empty choices parameter:



jurisdiction = forms.ChoiceField(choices=())


(For the sake of completeness: if you did need to use ModelChoiceField you can put anything you like into the queryset parameter when you're overwriting it in __init__, because it will never be evaluated. But managers have a none method which returns an empty queryset, so you could do queryset=State.objects.none().)






share|improve this answer























  • Cool, thanks Daniel. I'll make these changes tonight and let you know if I have any issues. You should have a page where people can donate money to you for your excellent help. I'd make a donation :) Thanks again for all of your help!

    – Jason Howard
    Nov 14 '18 at 0:28















0














As I mentioned, ModelChoiceField is not the right thing to do here. That's for allowing the user to choose from related items from a single model that will be saved into a ForeignKey. You don't have a ForeignKey, and what's more you're setting the choices attribute in your init rather than queryset. You should make it a plain ChoiceField with an empty choices parameter:



jurisdiction = forms.ChoiceField(choices=())


(For the sake of completeness: if you did need to use ModelChoiceField you can put anything you like into the queryset parameter when you're overwriting it in __init__, because it will never be evaluated. But managers have a none method which returns an empty queryset, so you could do queryset=State.objects.none().)






share|improve this answer























  • Cool, thanks Daniel. I'll make these changes tonight and let you know if I have any issues. You should have a page where people can donate money to you for your excellent help. I'd make a donation :) Thanks again for all of your help!

    – Jason Howard
    Nov 14 '18 at 0:28













0












0








0







As I mentioned, ModelChoiceField is not the right thing to do here. That's for allowing the user to choose from related items from a single model that will be saved into a ForeignKey. You don't have a ForeignKey, and what's more you're setting the choices attribute in your init rather than queryset. You should make it a plain ChoiceField with an empty choices parameter:



jurisdiction = forms.ChoiceField(choices=())


(For the sake of completeness: if you did need to use ModelChoiceField you can put anything you like into the queryset parameter when you're overwriting it in __init__, because it will never be evaluated. But managers have a none method which returns an empty queryset, so you could do queryset=State.objects.none().)






share|improve this answer













As I mentioned, ModelChoiceField is not the right thing to do here. That's for allowing the user to choose from related items from a single model that will be saved into a ForeignKey. You don't have a ForeignKey, and what's more you're setting the choices attribute in your init rather than queryset. You should make it a plain ChoiceField with an empty choices parameter:



jurisdiction = forms.ChoiceField(choices=())


(For the sake of completeness: if you did need to use ModelChoiceField you can put anything you like into the queryset parameter when you're overwriting it in __init__, because it will never be evaluated. But managers have a none method which returns an empty queryset, so you could do queryset=State.objects.none().)







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 13 '18 at 8:59









Daniel RosemanDaniel Roseman

457k42593650




457k42593650












  • Cool, thanks Daniel. I'll make these changes tonight and let you know if I have any issues. You should have a page where people can donate money to you for your excellent help. I'd make a donation :) Thanks again for all of your help!

    – Jason Howard
    Nov 14 '18 at 0:28

















  • Cool, thanks Daniel. I'll make these changes tonight and let you know if I have any issues. You should have a page where people can donate money to you for your excellent help. I'd make a donation :) Thanks again for all of your help!

    – Jason Howard
    Nov 14 '18 at 0:28
















Cool, thanks Daniel. I'll make these changes tonight and let you know if I have any issues. You should have a page where people can donate money to you for your excellent help. I'd make a donation :) Thanks again for all of your help!

– Jason Howard
Nov 14 '18 at 0:28





Cool, thanks Daniel. I'll make these changes tonight and let you know if I have any issues. You should have a page where people can donate money to you for your excellent help. I'd make a donation :) Thanks again for all of your help!

– Jason Howard
Nov 14 '18 at 0:28



















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%2f53276429%2fsetting-queryset-within-forms-modelchoicefield%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

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế