On Saturday 28 January 2017 18:21:34 Mike08 wrote:
> now my question is in the admin when the user attempts to create a new
> modelStudent for the field "user" all available users are shown in
> the drop down. My question is if there is a way for me to
> limit/restrict that drop down to a certain value or (set that drop
> down value to something and then have the drop down disabled) ? I
> only want people creating
> modelStudentAdmin under their respective user field.
Set a custom form, exclude the User field and in the clean method of that form, set the user to request.user.
--
Melvyn Sopacua
class modelStudentAdmin(admin.ModelAdmin): form = modelStudentAdminForm #Only display students that belong to this user
def get_queryset(self, request): qs = super(modelStudentAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: # Get the school instance schoolInstance = modelSchool.objects.get(user=request.user) qs = modelStudent.objects.filter(school=schoolInstance) return
qs def get_form(self, request, obj=None, **kwargs): self.fields["first_name"] = "asasa" #modelStudentAdmin.form['first_name']="FooUSerFs" #modelStudentAdmin.form.cleaned_data.setdefault("first_name","dsdsds")
#modelStudentAdmin.form.initial={"first_name":"JoeJoe"} #form.cleaned_data.get('player') return modelStudentAdmin.form
On Saturday 28 January 2017 21:48:03 Mike08 wrote:
> Ok that makes sense.
>
> Now I have something like this
>
> class modelStudentAdmin(admin.ModelAdmin):
> form = modelStudentAdminForm
>
> #Only display students that belong to this user
> def get_queryset(self, request):
> qs = super(modelStudentAdmin, self).get_queryset(request)
>
> if request.user.is_superuser:
> return qs
> else:
> # Get the school instance
> schoolInstance =
> modelSchool.objects.get(user=request.user) qs =
> modelStudent.objects.filter(school=schoolInstance) return qs
>
> def get_form(self, request, obj=None, **kwargs):
This self isn't the form. It's the model admin and should return a ModelForm. The docs I linked has a complete example you can build on.
--
Melvyn Sopacua