【问题标题】:Django - int() argument must be a string, a bytes-like object or a number, not 'Association'Django - int() 参数必须是字符串、类似字节的对象或数字,而不是“关联”
【发布时间】:2017-07-29 17:29:00
【问题描述】:

我想使用下拉列表注册管理员,您可以选择关联并创建一个 AdministratorAssociation 之间的关系。

我有什么遗漏吗?

还是个新手,感谢你们的帮助,伙计们!

管理员\models.py

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


    class Meta:
        db_table = 'Administrator'

成员\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()})

【问题讨论】:

    标签: python django python-2.7 python-3.x django-forms


    【解决方案1】:

    关联返回对象的清理数据,因此您可以编辑这些行:

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

    到:

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

    它会正常工作的!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多