【问题标题】:Django - Easiest way to set initial value for form fields to the current database value, for custom UserChangeForm?Django - 为自定义 UserChangeForm 将表单字段的初始值设置为当前数据库值的最简单方法?
【发布时间】:2019-10-11 15:38:10
【问题描述】:

基本上我有一个使用我的用户模型“Writer”的自定义 UserChangeForm,我想将所有字段的默认值设置为数据库的当前值(或请求用户的值)。解决此问题的最佳方法是什么?

我尝试在表单中设置默认值,但是在 forms.py 中无法访问请求对象

表格...

class writerChangeForm(UserChangeForm):

    class Meta:
        model = Writer
        fields = ('username', 'email', 'first_name', 'last_name', 'country')
        country = CountryField().formfield()
        widgets = {'country': CountrySelectWidget()}

景色...

class ProfileView(generic.CreateView):
    form_class = writerChangeForm
    template_name = 'diary/profile.html'

感谢您的任何意见!

【问题讨论】:

    标签: django forms field default


    【解决方案1】:

    最好的方法是覆盖get_initial() 方法。

    class ProfileView(generic.CreateView):
        form_class = writerChangeForm
        template_name = 'diary/profile.html'
    
        def get_initial(self):
            # get_initial should return dict. They should be rendered in template.
            writer = Writer.objects.get(pk=1) # first get data from database.
            # dictionary key names should be same as they are in forms.
            return {
                'username': writer.username,
                'email': writer.email,
                'first_name': writer.first_name
            }
    

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 2014-04-18
      • 1970-01-01
      • 2010-10-23
      • 2019-03-20
      • 2018-05-22
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      相关资源
      最近更新 更多