如何在注册表单中添加Foreginkey字段?

时间:2018-08-27 07:52:00

标签: django django-models django-forms

我正在创建一个注册表单。我继承了注册类。想添加一个选择列表(外键)。出现错误。

model.py

class Branch(models.Model):
    status = (
        ('active', 'Active'),
        ('shutdown', 'Shutdown'),
        ('opensoon', 'Opening Soon'),
    )
    branch_name = models.CharField(max_length=10, unique=True)
    availablity_status = models.CharField(choices=status, default='available', max_length=13 )
    branch_state = models.CharField(max_length=20, name='State')

    def __str__(self):
        return self.branch_name

form.py

class SignUpForm(UserCreationForm):
    branch_name = forms.ForeignKey(Branch, on_delete=models.CASCADE)

    class Meta:
        model = User
        fields = ('username','branch_name','password1','password2')
        widgets = {
         'username': forms.TextInput(attrs={'size': 15, 'placeholder':     'Username'})
    }

错误:

 branch_name = forms.ForeignKey(Branch, on_delete=models.CASCADE)
 AttributeError: module 'django.forms' has no attribute 'ForeignKey'

2 个答案:

答案 0 :(得分:2)

解决方案

对于此特定查询,您需要按如下方式使用forms.py,切记为您希望用户选择的对象传递查询集。

因此,我将您的class SignUpForm(UserCreationForm): ... branch_name = forms.ModelChoiceField(queryset = Branch.objects.all()) ... 修改为:

class SignUpForm(UserCreationForm):
    ...
    branch_name = forms.ModelMultipleChoiceField(queryset = Branch.objects.all())
    ...

...或者如果您需要选择多个分支:

ModelChoiceField

可选的专业提示扩展 pk

如果您不想只显示Branch模型的PrimaryKey / ID(branch_name)(而是返回fields.py),甚至可以添加以下内容:

from django.forms import ModelChoiceField class MyBranchModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "Branch: #%i" % obj.branch_name

branch_name = forms.MyBranchModelChoiceField(queryset = Branch.objects.all())

然后使用类似于上面的内容:

SELECT LIST1, 
       LIST2, 
       CASE 
          WHEN (([LIST1] LIKE '%APR%' 
                 OR [LIST1] LIKE '%NOLA%') 
           OR ([LIST2] NOT LIKE '%APR%' 
                AND [LIST2] NOT LIKE '%NOLA%')) 
          THEN 1 
          ELSE 0 
       END AS RESULTS

LIST1   LIST2   RESULTS
APRIL   NOLA    1
NOLA    BEBB    1
NOLA    APROLS  1
APRA    BLIN    1

答案 1 :(得分:1)

class SignUpForm(UserCreationForm):
   branch_name = forms.ModelChoiceField(queryset=Branch.objects.all())

  class Meta:
      model = User
      fields = ('username','branch_name','password1','password2')
      widgets = {
         'username': forms.TextInput(attrs={'size': 15, 'placeholder':     'Username'})
    }

您也可以像这样对select下拉列表进行操作,否则通常它将以值作为主键并标记您返回的内容,如果您需要Branch的名称或其他详细信息,也可以使用第二个

class SignUpForm(UserCreationForm):
       branch_name = forms.ChoiceField(choices=[(o.id, str(o)) for o in Branch.objects.all()])

      class Meta:
          model = User
          fields = ('username','branch_name','password1','password2')
          widgets = {
             'username': forms.TextInput(attrs={'size': 15, 'placeholder':     'Username'})
        }