Niknak
Niknak

Reputation: 593

Django - int() argument must be a string, a bytes-like object or a number, not 'Association'

I want to register an admin with a dropdown-list you can choose association and create a relation between Administrator and Association.

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)
    member_no = models.ForeignKey(Member)

    class Meta:
        db_table = 'Association'

    def __str__(self):
        return self.asoc_name

forms.py

class SignUpForm(forms.ModelForm):
    ...
    association = forms.ModelChoiceField(queryset=Association.objects.all())
     ...


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

views.py

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if not form.is_valid():
            return render(request, 'admin/signup.html',
                          {'form': form})

        else:
            ...
            asoc_pk = form.cleaned_data.get('association')
            asoc = Association.objects.get(pk=asoc_pk)
            ...
            Administrator.objects.create_user(...
                                              association=asoc,    
                                              ...)
            user = authenticate(...
                                association=asoc,
                                ...)
            return redirect('/')

    else:
        return render(request, 'admin/signup.html',
                      {'form': SignUpForm()})

Upvotes: 0

Views: 1072

Answers (1)

Amin Sabbaghian
Amin Sabbaghian

Reputation: 401

Cleaned data for association returns object, so you can edit these lines:

asoc_pk = form.cleaned_data.get('association')
asoc = Association.objects.get(pk=asoc_pk)

to:

asoc = form.cleaned_data.get('association')

and it'll work fine!

Upvotes: 2

Related Questions