在基于Django类的视图中,从上下文数据设置初始表单域值 [英] Setting initial formfield value from context data in Django class based view

查看:269
本文介绍了在基于Django类的视图中,从上下文数据设置初始表单域值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个激活URL,其中包含激活密钥(/ user / activate / 123123123)。这没有任何问题。 get_context_data可以将其移动到模板中。我想做的是将其作为关键字段的初始值,以便用户只需输入注册时创建的用户名和密码。



如何拉来自context或get()的关键字没有将字段硬编码到模板中?

  class ActivateView(FormView):
template_name ='activate.html'
form_class = ActivationForm
#initial = {'key':'123123123'}< - 这是有用的,但是没用

success_url = 'profile'

def get_context_data(self,** kwargs):
if'activation_key'in self.kwargs:
context = super(ActivateView,self).get_context_data(* * kwargs)
上下文['activation_key'] = self.kwargs ['activation_key']

这是我期望为我设置的值,但它不' t似乎工作
上面的上下文工作正常,但是我将不得不手动构建
表单中的模板非常unDjango。

self.initial ['key'] = self.kwargs ['activation_key']
return context
else:
return super(ActivateView,self ).get_context_data(** kwargs)


解决方案

get_initial 提供动态初始参数:

 类ActivationView(FormView): 
#...

def get_initial(self):
return {'key':self.kwargs ['activation_key']}


I've got an activation url that carries the activation key ( /user/activate/123123123 ). That works without any issue. get_context_data can plop it into the template fine. What I want to do is have it as an initial value for the key field so the user only needs to enter username and password as created at registration.

How can I pull the key from context or get() without hardcoding the field into the template?

class ActivateView(FormView):
    template_name = 'activate.html'
    form_class = ActivationForm
    #initial={'key': '123123123'} <-- this works, but is useless

    success_url = 'profile'

    def get_context_data(self, **kwargs):
        if 'activation_key' in self.kwargs:
            context = super(ActivateView, self).get_context_data(**kwargs)
            context['activation_key'] = self.kwargs['activation_key']
            """
            This is what I would expect to set the value for me. But it doesn't seem to work.
            The above context works fine, but then I would have to manually build the 
            form in the  template which is very unDjango.
            """
            self.initial['key'] = self.kwargs['activation_key']  
            return context
        else:
            return super(ActivateView, self).get_context_data(**kwargs)

解决方案

You can override get_initial to provide dynamic initial arguments:

class ActivationView(FormView):
    # ...

    def get_initial(self):
        return {'key': self.kwargs['activation_key']}

这篇关于在基于Django类的视图中,从上下文数据设置初始表单域值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆