django将request传入Form

Posted 本站大佬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django将request传入Form相关的知识,希望对你有一定的参考价值。

forms.py

class Personal_data_Form(forms.ModelForm):
    nickname = forms.CharField(max_length=20,help_text='长度控制在20个字内',label='昵称')
    self_introduction = forms.CharField(max_length=200,empty_value = 'aa',strip='sss',label='个人介绍')
#加入request=None
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=None,
                 empty_permitted=False, instance=None, use_required_attribute=None,
                 renderer=None,request=None):
        opts = self._meta
        if opts.model is None:
            raise ValueError('ModelForm has no model class specified.')
        if instance is None:
            # if we didn't get an instance, instantiate a new one
            self.instance = opts.model()
            object_data = {}
        else:
            self.instance = instance
            object_data = model_to_dict(instance, opts.fields, opts.exclude)
        # if initial was provided, it should override the values from instance
        if initial is not None:
            object_data.update(initial)
        # self._validate_unique will be set to True by BaseModelForm.clean().
        # It is False by default so overriding self.clean() and failing to call
        # super will stop validate_unique from being called.
        self._validate_unique = False
        super().__init__(
            data, files, auto_id, prefix, object_data, error_class,
            label_suffix, empty_permitted, use_required_attribute=use_required_attribute,
            renderer=renderer,
        )
        #如果request存在,则进行操作
        if request:
            user = request.user
            self.fields['nickname'].initial = user.nickname
            self.fields['email'].initial = user.email
            self.fields['self_introduction'].initial = user.self_introduction
        for formfield in self.fields.values():
            apply_limit_choices_to_to_formfield(formfield)

    class Meta:
        model = AccountUser
        fields = ('nickname','email','self_introduction')

views.py

forms = Personal_data_Form(request=request)

以上是关于django将request传入Form的主要内容,如果未能解决你的问题,请参考以下文章

Django将request对象传入模板配置

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)(代码片段

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)(代码片段

如何在Django视图中使用for循环返回每次迭代[关闭]

Django框架form表单配合ajax注册

Django之中间件与form其他用法