问题
I have a model Member that includes a specification called member_id.
class Member(models.Model):
member_id = models.SlugField(max_length=10)
name = models.CharField(max_length=200)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
mobile = models.SlugField(max_length=20)
def __str__(self):
return self.name
I want to create a drop-down menu of stored member ID's for the user to choose from in select_member.html
.
Right now, I have this in forms.py: (pretty sure it's wrong)
class SelectForm(forms.Form):
memberid = forms.ModelChoiceField(queryset=Member.member_id.objects.all())
The following view:
class SelectView(generic.ListView):
template_name = 'expcore/select_member.html'
model = Activity
def select_member(request):
form = SelectForm()
if request.method == 'POST':
form = SelectForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/questions/')
else:
form = SelectForm()
return render(request, 'select_member.html', {'form': form})
The url:
url(r'^activity/(?P<activityname>[^/]+)/member/$', views.SelectView.as_view(), name='select_member'),
And nothing in my select_member.html because I'm not sure what to put.
Can someone help me out with the form, view, and HTML? I want to be able to call all the member IDs but Member.member_id.objects.all() doesn't work.
Also, it would be great if someone could tell me how to correctly call all the stored member IDs - instead of the incorrect Member.member_id.objects.all().
回答1:
Member.objects.values('member_id') gives you list of dictionaries with values structured as {'member_id': value}.
If you just want the ids, you can make Member.objects.values_list('member_id', flat=True) which will just give you list of member ids.
Anyways you try to use ModelChoiceField which expects a queryset of Model instances and you try to pass to it a list of slugs.
What you want to do is
ModelChoiceField(queryset=Member.objects.all(), to_field_name='member_id')
Normally ModelChoiceFields
gets id as option, but you can override it with to_field_name
:
https://github.com/django/django/blob/master/django/forms/models.py#L1129-L1144
来源:https://stackoverflow.com/questions/33952821/creating-a-drop-down-menu-of-member-ids