django: how to display choices in form's ChoiceField depending on the current user's data
I have the following form with 4 fields:
from django import forms
from django.apps import apps
from .models import Task
CustomUser = apps.get_model('users', 'CustomUser')
students = CustomUser.objects.filter(status='student')
students_choices = [(student.username, student) for student in students]
class AddTaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ('title', 'description', 'deadline', 'student')
widgets = {
'deadline': forms.SelectDateWidget(),
}
student = forms.ChoiceField(choices=students_choices)
The "student" field will display the choices with all users with status "student". But what if I want the queryset to be:
students = CustomUser.objects.filter(status='student', username__in=user.students.split())
How can I get user here?
django django-forms
add a comment |
I have the following form with 4 fields:
from django import forms
from django.apps import apps
from .models import Task
CustomUser = apps.get_model('users', 'CustomUser')
students = CustomUser.objects.filter(status='student')
students_choices = [(student.username, student) for student in students]
class AddTaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ('title', 'description', 'deadline', 'student')
widgets = {
'deadline': forms.SelectDateWidget(),
}
student = forms.ChoiceField(choices=students_choices)
The "student" field will display the choices with all users with status "student". But what if I want the queryset to be:
students = CustomUser.objects.filter(status='student', username__in=user.students.split())
How can I get user here?
django django-forms
add a comment |
I have the following form with 4 fields:
from django import forms
from django.apps import apps
from .models import Task
CustomUser = apps.get_model('users', 'CustomUser')
students = CustomUser.objects.filter(status='student')
students_choices = [(student.username, student) for student in students]
class AddTaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ('title', 'description', 'deadline', 'student')
widgets = {
'deadline': forms.SelectDateWidget(),
}
student = forms.ChoiceField(choices=students_choices)
The "student" field will display the choices with all users with status "student". But what if I want the queryset to be:
students = CustomUser.objects.filter(status='student', username__in=user.students.split())
How can I get user here?
django django-forms
I have the following form with 4 fields:
from django import forms
from django.apps import apps
from .models import Task
CustomUser = apps.get_model('users', 'CustomUser')
students = CustomUser.objects.filter(status='student')
students_choices = [(student.username, student) for student in students]
class AddTaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ('title', 'description', 'deadline', 'student')
widgets = {
'deadline': forms.SelectDateWidget(),
}
student = forms.ChoiceField(choices=students_choices)
The "student" field will display the choices with all users with status "student". But what if I want the queryset to be:
students = CustomUser.objects.filter(status='student', username__in=user.students.split())
How can I get user here?
django django-forms
django django-forms
asked Nov 21 '18 at 19:37
user10687617user10687617
31
31
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
First of all, do not do the query on module level:
students = CustomUser.objects.filter(status='student')
This line will execute only one time (at the application start).
So to answer to your question:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['student'] = forms.ChoiceField(choices=((student.id, student.username) for student in custom_queryset))
And this is of course the AddTaskForm init
Wonder if this is some kind of a student task ;)
Happy coding.
I've tried this before, but got an error because I didn't know that super() must be called before the assignment. Thanks anyway.
– user10687617
Nov 21 '18 at 20:01
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53419397%2fdjango-how-to-display-choices-in-forms-choicefield-depending-on-the-current-us%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
First of all, do not do the query on module level:
students = CustomUser.objects.filter(status='student')
This line will execute only one time (at the application start).
So to answer to your question:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['student'] = forms.ChoiceField(choices=((student.id, student.username) for student in custom_queryset))
And this is of course the AddTaskForm init
Wonder if this is some kind of a student task ;)
Happy coding.
I've tried this before, but got an error because I didn't know that super() must be called before the assignment. Thanks anyway.
– user10687617
Nov 21 '18 at 20:01
add a comment |
First of all, do not do the query on module level:
students = CustomUser.objects.filter(status='student')
This line will execute only one time (at the application start).
So to answer to your question:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['student'] = forms.ChoiceField(choices=((student.id, student.username) for student in custom_queryset))
And this is of course the AddTaskForm init
Wonder if this is some kind of a student task ;)
Happy coding.
I've tried this before, but got an error because I didn't know that super() must be called before the assignment. Thanks anyway.
– user10687617
Nov 21 '18 at 20:01
add a comment |
First of all, do not do the query on module level:
students = CustomUser.objects.filter(status='student')
This line will execute only one time (at the application start).
So to answer to your question:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['student'] = forms.ChoiceField(choices=((student.id, student.username) for student in custom_queryset))
And this is of course the AddTaskForm init
Wonder if this is some kind of a student task ;)
Happy coding.
First of all, do not do the query on module level:
students = CustomUser.objects.filter(status='student')
This line will execute only one time (at the application start).
So to answer to your question:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['student'] = forms.ChoiceField(choices=((student.id, student.username) for student in custom_queryset))
And this is of course the AddTaskForm init
Wonder if this is some kind of a student task ;)
Happy coding.
answered Nov 21 '18 at 19:46
opalczynskiopalczynski
1,035810
1,035810
I've tried this before, but got an error because I didn't know that super() must be called before the assignment. Thanks anyway.
– user10687617
Nov 21 '18 at 20:01
add a comment |
I've tried this before, but got an error because I didn't know that super() must be called before the assignment. Thanks anyway.
– user10687617
Nov 21 '18 at 20:01
I've tried this before, but got an error because I didn't know that super() must be called before the assignment. Thanks anyway.
– user10687617
Nov 21 '18 at 20:01
I've tried this before, but got an error because I didn't know that super() must be called before the assignment. Thanks anyway.
– user10687617
Nov 21 '18 at 20:01
add a comment |
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.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53419397%2fdjango-how-to-display-choices-in-forms-choicefield-depending-on-the-current-us%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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