0

django noob here. The question i am going to ask has been asked several times, however, i couldn't find the answers which can help my case.

the query is: I have a Form having a choice field which loads its choices information from the database. Basically, I have designed my models in such a way that, the choices displayed is individual to the users.

for example: for user1, the choice field shows a,b,c,d. where as for user 2, the choice field shows v,w,d.

The problem i am facing is referencing the logged in user and getting the username. then pass the username as the filter to the database.

I have come across numerous init functions trying to do this, somehow it is not helping my case.

forms.py

class class_model(forms.Form):
    class_name = forms.ChoiceField(
                    required=False,
                    widget=forms.Select,
                )

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super (class_model, self).__init__(*args, **kwargs)
        current_user = self.user
        name = current_user.username
        k = User.objects.get(username=name)
        y = UserProfile.objects.get(user=k)
        schoolid = y.schoolid
        primary_filter = Class1.objects.filter (school_id=schoolid)
        ax = [("Choose Class", "Choose Class")] + list (primary_filter.objects.values_list ('class_name', 'class_name').distinct())
        self.fields['class_name'].choices = ax

The error i receive: 'QueryDict' object has no attribute 'username'

Update:

views.py

            @login_required(login_url="login/")
            def create(request):
                print(request.method)
                if request.method == 'POST':
                    form2 = class_model(request.POST, request.user)
                    if form2.is_valid():
                        class_name = form2.cleaned_data['class_name']
                    return render(request, 'create_student.html', {'form2': form2}
                else:       
                    print(form.errors)
                    return render(request, 'create_student.html', {'form2': form2})

1 Answers1

0

You've told the form to expect the user as the first positional parameter, so you need to pass it there.

form2 = class_model(request.user, data=request.POST)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I tried it. The error still persists. I receive a "'QuerySet' object has no attribute 'objects'" error. Does the error has anything to do with the form (how I am trying to load the user information in the init function?) – user2279701 Nov 05 '17 at 15:53
  • Any help will be really appreciated. Requesting assistance with this query. – user2279701 Nov 07 '17 at 05:37
  • Please show the updated code and the full traceback, as an edit to your question. – Daniel Roseman Nov 07 '17 at 07:48