Skip to main content
 首页 » 编程设计

python之Django——预填充隐藏字段

2025年05月04日33soundcode

在我的用户注册过程中,用户首先创建他们的帐户,然后创建一个 LIST 对象,然后被定向到他们刚刚创建的 LIST 对象的仪表板。为此,我需要能够访问最近创建的 LIST 对象的 list_id,以便将其传递到下一个 View /模板。 list_id 是 LIST 表/类的主键,因此我不希望用户为此创建一个值——它会自动递增。这是模型中的字段:

class List(models.Model): 
    list_id = models.IntegerField(primary_key=True) 

MySQL 中 list_id 的描述:

+---------------+--------------+------+-----+---------+----------------+ 
| Field         | Type         | Null | Key | Default | Extra          | 
+---------------+--------------+------+-----+---------+----------------+ 
| list_id       | int(11)      | NO   | PRI | NULL    | auto_increment | 

这是 View :

@login_required 
@permission_required('social_followup.add_list') 
def user_create(request): 
    if request.method == 'POST': 
        list_form = forms.ListForm(request.POST) 
        if list_form.is_valid(): 
            list_create = list_form.save() 
            messages.success(request, 'List {0} created'.format(list_create.list_id)) 
            up, _ = UserProfile.objects.get_or_create(user=request.user, list_id=list_create) 
            return redirect(reverse('user_dashboard', args=(2,)))  # 2 is just an example 
    else: 
        list_form = forms.ListForm() 
 
    return TemplateResponse(request, 'dashboard/create.html', {'list_form': list_form, }) 

但是,我发现当我不将 list_id 作为表单的一部分时,我无法访问该属性(当 list_id 不是 field )。在我的模板中,我隐藏了 list_id 字段,如下所示:

<div class="control-group {% if list_form.list_id.errors %}error{% endif %}"> 
    <div class="controls"> 
        {{ list_form.list_id.as_hidden }} 
    </div> 
</div> 

由于 list_id 是必需的并且是隐藏的,因此表单将无法验证,因为 list_id 没有值。但是,如果我将 list_id 作为字段删除,我似乎无法在我的 View 中访问 list_id 属性。有没有办法用下一个 list_id 自动填充此字段,以便我可以使用 list_create.list_id 获取值,并隐藏该字段?或者有其他方法可以实现吗?

请您参考如下方法:

在调用 .save() 之前主键不存在。如果您想在保存表单后稍后访问 PK,您可以通过传递给您的模板来访问它

list_form = forms.ListForm(instance=list_create)

然后在你的模板中

{{list_form.instance.id}}