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})