python - Django 将参数传递给 CreateView 并用它填充表单

标签 python django

我想创建一个 CreateView,其中的表单已经完成,并带有将从另一个 View 传递给它的参数。

这是带有输入字段的初始 View 。像这样:

<form role="form" action="" method="post">
    {% csrf_token %}
    <div class="col-sm-6">
      <div class="form-group">
        <div class="form-line">
          <label>{{form.cpf.label}}</label><strong style="color:red;"> *</strong>
          {% if form.cpf.errors %}<label class="error">{% for error in form.cpf.errors %}{{error}}{% endfor %}</label>{% endif %}
          {{form.cpf}}
        </div>
      </div>
    </div>
    <button class="btn btn-success foot-btn" type="submit"><i style="vertical-align:middle" class="material-icons">add</i><span style="vertical-align:middle">Verificar</span></button>
</form>

当用户提交此表单时,他将被重定向到另一个页面。询问他是否想将该值插入数据库中。

现在我正在尝试像这样重定向,尝试将 POST 值作为参数传递给 CreateView

return redirect(reverse('blacklist:addcpfview', args=(request.POST['cpf'],)))

但是我似乎无法在CreateView中获取这个参数。

我知道我目前的做法可能是非常错误的,但我是 Django 的初学者,想知道最好的方法。

更新

CreateView

class AdicionarCPFView(CreateView):
    form_class = CPFForm
    template_name = 'blacklist/cpf/addCPF.html'
    success_url = reverse_lazy('blacklist:cpfselectview')

    def get_context_data(self, **kwargs):
        context = super(CreateView, self).get_context_data(**kwargs)
        context['title_complete'] = 'Adicionar CPF'
        return context

最佳答案

当您使用CreateView时 - 它有一个特殊的方法来填充初始值 - get_initial

您需要的是重写此方法并从其中的 kwargs 读取变量。

def get_initial(self):
    initial = super().get_initial()
    # cpf - it's the name of the field on your current form
    # self.args will be filled from URL. I'd suggest to use named parameters
    # so you can access e.g. self.kwargs['cpf_initial']
    initial['cpf'] = self.args[0] 
    return initial

实现此目的的另一种方法是使用 session 。

因此,在重定向之前,请执行 request.session['initial_cpf'] = request.POST['cpf]
在创建 View 中,您访问的不是 self.args 而是 self.request.session

还有一个旁注 - 在第一个 View 中,最好不要从 POST 读取变量,而是使用表单。

关于python - Django 将参数传递给 CreateView 并用它填充表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46875619/

相关文章:

python - 我想在 python 代码中添加 ssl 证书,但我不知道如何在代码中添加它

python - Django-hvad TranslatableAdmin 出现管理器错误

python - Python 3-optparse-发生错误时如何更改返回值

python - Django 查询集与 distinct 和 exclude 一起

python - django.core.exceptions.FieldDoesNotExist : model has no field named <function SET_NULL at 0x7fc5ae8836e0>

python - MySQL游标背后的概念

python - django 不读我的 models.py

python - virtualenv 上的 pip install requests[security] 无法构建密码学和 cffi 轮子

database - Django 自定义字段的属性进行数据库查询

python - 映射后的数字格式?