初始化外键下拉

时间:2010-03-02 18:01:00

标签: django forms initialization

我想在我的一个表单中填充两个外键字段。相关的代码位如下:

if request.method == 'POST':
    form = IssuesForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        form.save()
else:
    form = IssuesForm(initial={'vehicle': stock_number, 'addedBy': request.user, })

vehicle指向Vehicle课程。 addedBy将包含当前登录的用户。

然而,根据我的意愿,下拉没有初始化......我仍然需要选择车辆和用户。从这里我有两个问题:

  1. 可能是什么问题?
  2. 将这些表单设为只读的最佳方法是什么?
  3. 编辑1 到目前为止,IssueForm类看起来像这样:

    class Issues(models.Model):
       vehicle = models.ForeignKey(Vehicle)
       description = models.CharField('Issue Description', max_length=30,)
       type = models.CharField(max_length=10, default='Other', choices=ISSUE_CHOICES)
       status = models.CharField(max_length=12, default='Pending', 
         choices=ISSUE_STATUS_CHOICES)
       priority = models.IntegerField(default='8', editable=False)
       addedBy = models.ForeignKey(User, related_name='added_by')
       assignedTo = models.CharField(max_length=30, default='Unassigned')
       dateTimeAdded = models.DateTimeField('Added On', default=datetime.today, 
         editable=False)
       def __unicode__(self):    
        return self.description
    

    表格类

    class IssuesForm(ModelForm):   
      class Meta:
        model = Issues
        exclude = ('assignedTo')
    

2 个答案:

答案 0 :(得分:1)

对于第二个问题,您是否要将addedBy字段设为只读?如果是这样,请不要将其添加到您的表单中(如果您将其呈现给用户,它将永远不会是只读的,例如Firebug)。您可以在保存方法中填充它。

if request.method == 'POST':
    form = IssuesForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        issue = form.save(commit=False)
        issue.addedBy = request.user
        # any other read only data goes here
        issue.save()
else:
    form = IssuesForm(initial={'vehicle': stock_number}) # this is related to your first question, which I'm not sure about until seeing the form code

答案 1 :(得分:0)

要使表单只读:在表单类上,覆盖__init__method以禁用html字段:

def __init__(self, *args, **kwargs):
    super(IssuesForm, self).__init__(*args, **kwargs)
    for key in self.fields.keys():
        self.fields[key].widget.attrs = {'disabled': 'disabled'}

确保您也不听POST请求,如果是,请不要保存表单。 您可以进一步自定义__init__method以获取一些参数,并在调用super方法后将字段设置为这些值。