2

I want to create a field in a form for superuser. This field should have a list of all the staff users in a drop down manner so that superuser can select one of them to assign him/her a task. How should I create the drop down list?

So far, I can display the users like this:

from django.contrib.auth.models import User

users = User.objects.all()
uitwaa
  • 615
  • 1
  • 12
  • 24

2 Answers2

1

You can use ModelChoiceField for this. Just add to form class something like this:

user = forms.ModelChoiceField(queryset=User.objects.filter(is_staff=True), empty_label=None)
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • I'm getting this error: 'module' object has no attribute 'ModelChoiceField' – uitwaa Jul 08 '17 at 17:30
  • How can I print the name of the selected user in template? – uitwaa Jul 08 '17 at 18:48
  • @uitwaa in view you can get selected user from form's `cleaned_data`: `user=form.cleaned_data['user']` and then pass this value as template context: `return render(request, 'post_form.html', {'selected_user':user})`. Then in template you can do `{{selected_user}}`. Or if you need user before form submition you can use javascritp: https://stackoverflow.com/questions/11563638/how-do-i-get-the-value-of-text-input-field-using-javascript – neverwalkaloner Jul 08 '17 at 18:50
  • I tried it but it doesn't display. Actually, I'm trying to modify posts app- https://github.com/codingforentrepreneurs/Advancing-the-Blog/tree/master/src/posts – uitwaa Jul 08 '17 at 19:58
  • @uitwaa sorry I cannot help you without understanding what actually you done and related code. I think you'd better post another question with details. – neverwalkaloner Jul 09 '17 at 03:24
  • https://stackoverflow.com/questions/45001409/fetch-data-from-form-and-display-in-template?noredirect=1#comment76992479_45001409 – uitwaa Jul 10 '17 at 17:43
0
class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
         if db_field.name == "cars":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
         return super().formfield_for_manytomany(db_field, request, **kwargs)

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey

aman kumar
  • 3,086
  • 1
  • 17
  • 24