Niknak Niknak - 9 months ago 30
Python Question

'QueryDict' object has no attribute 'association'

Admin (who are logged in) wants to register a member with same association-name as admin but it throws this error.

Is there something i'm missing?

Still a newbie so appreciate your help, folks!

admin\models.py

class Administrator(AbstractUser):
...
association= models.ForeignKey(Association)


class Meta:
db_table = 'Administrator'


member\models.py

from pl.admin.models import Administrator


class Association(models.Model):
asoc_name = models.CharField(max_length=100)

class Meta:
db_table = 'Association'

def __str__(self):
return self.asoc_name





forms.py

class RegForm(forms.ModelForm):
...
association = forms.ModelChoiceField(queryset=Association.objects.none())
...


class Meta:
model = Administrator
fields = [..., 'association', ...]

def __init__(self, user, *args, **kwargs):
super(RegForm, self).__init__(*args, **kwargs)
self.fields['association'].queryset = Association.objects.filter(
asoc_name=user.association)





views.py

def member_signup(request):
if request.method == 'POST':
form = RegForm(request.POST, request.user)
if not form.is_valid():
return render(request, 'member/member_signup.html',
{'form': form})

else:
...
asoc = form.cleaned_data.get('association')
...
Member.objects.create(...
association=asoc,
...)
user = authenticate(...
association=asoc,
...)
return redirect('/')

else:
return render(request, 'member/member_signup.html',
{'form': RegForm(request.user)})





EDIT with traceback

Traceback (most recent call last):
File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\...\member\views.py", line 184, in member_signup
form = RegForm(request.POST, request.user)
File "C:\...\member\forms.py", line 113, in __init__
self.fields['association'].queryset = Association.objects.filter(asoc_name=user.association)
AttributeError: 'QueryDict' object has no attribute 'association'

Answer Source

user is the first parameter to your form, but in your if clause you're passing it as the second paramter, after request.POST.

Generally you should avoid changing the signature of the form instantiation; instead you should pass the user as a keyword argument and get it from kwargs.