1

This is my views.py

def new_note(request):
    form = NoteForm(request.POST, user=request.user)
    . . .
    return render(request, 'newNote.html', {'note_form': NoteForm, 'registered': registered})

This is my forms.py

class NoteForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        # self.user = kwargs.pop('user', None)
        self.user = kwargs.pop('user')
        # self.validate = kwargs.pop('validate', False)
        super(NoteForm, self).__init__(*args, **kwargs)
        groups = StudentGroup.objects.filter(id_nauczyciela=self.user.pk)
        # print(self.user.pk)
        self.fields['id_groups'].queryset = groups

    note_name = forms.CharField(label="Note name", required=True)

    class Meta:
        model = Note
        fields = ('id_groups', 'id_students', 'note_name')

id_groups is ModelChoseField

In this code i try take logged user id.

When i try use it i got error KeyError 'user', when i change self.user = kwargs.pop('user') to self.user = kwargs.pop('user', None) i got error like this

AttributeError: 'NoneType' object has no attribute 'pk'

I am absolutely sure self.user.pk return value what i expected.

My question is How deal with this type of error?

1
  • please share your complete views.py Commented Dec 11, 2015 at 10:07

1 Answer 1

2

Your render completely ignores the form you've provided

return render(request, 'newNote.html', {'note_form': NoteForm, 'registered': registered})

Should be

return render(request, 'newNote.html', {'note_form': form, 'registered': registered})

This should solve the original key error issue you were having, the issue you found when changing the code would need different error handling

self.user = kwargs.pop('user', None)
# self.validate = kwargs.pop('validate', False)
super(NoteForm, self).__init__(*args, **kwargs)

if self.user is not None:
    groups = StudentGroup.objects.filter(id_nauczyciela=self.user.pk)
    # print(self.user.pk)
    self.fields['id_groups'].queryset = groups
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.