将变量从视图传递到表单 Django

Posted

技术标签:

【中文标题】将变量从视图传递到表单 Django【英文标题】:Pass Variable from View to Form Django 【发布时间】:2019-05-26 02:54:03 【问题描述】:

基本上,我使用password and username 向用户发送电子邮件。我可以使用self.cleaned_data.get('email') 获取用户名。但问题是我不知道如何从视图中获取密码,我在视图中设置随机密码。所以请帮我在def send_email中获取从views.py到forms.py的随机密码

Forms.py

class UserRegisterForm(forms.ModelForm):
        email = forms.EmailField()
        first_name = forms.CharField()
        last_name = forms.CharField()

        class Meta:
            model = User
            fields = ['first_name','last_name', 'email']

        def send_email(self):
            name = self.cleaned_data.get('first_name')
            username = self.cleaned_data.get('email')
            to_email = self.cleaned_data.get('email')
            password1 = # Get Password from view

Views.py

def register(request):
    if request.method == 'POST':
        ur_form = UserRegisterForm(request.POST)
        pr_form = UserProfileForm(request.POST, request.FILES)
        user_role = 0
        if ur_form.is_valid() and pr_form.is_valid():
            new_user = ur_form.save(commit=False)            
            new_user.username = new_user.email
            password = User.objects.make_random_password() # Pass This to Form send_email
            new_user.set_password(password)
            new_user.save()

【问题讨论】:

【参考方案1】:

表单初始化时将随机密码传递给表单,并通过覆盖 __init__() 方法在您的UserRegisterForm 表单中处理该密码

试试这个

# form.py
class UserRegisterForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self._pwd = kwargs.pop('pwd', None)
        super().__init__(*args, **kwargs)

    email = forms.EmailField()
    first_name = forms.CharField()
    last_name = forms.CharField()

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']

    def send_email(self):
        name = self.cleaned_data.get('first_name')
        username = self.cleaned_data.get('email')
        to_email = self.cleaned_data.get('email')
        password1 = self._pwd # access your password from view


# views.py
def register(request):
    if request.method == 'POST':
        random_password = generate_your_random_password() # generate password here 
        ur_form = UserRegisterForm(request.POST, pwd=random_password)
        pr_form = UserProfileForm(request.POST, request.FILES)
        user_role = 0
        if ur_form.is_valid() and pr_form.is_valid():
            new_user = ur_form.save(commit=False)
            new_user.username = new_user.email
            new_user.set_password(random_password) # set the random password here 
            new_user.save()
            # your code ....

【讨论】:

以上是关于将变量从视图传递到表单 Django的主要内容,如果未能解决你的问题,请参考以下文章

Django - 将变量从基于类的视图传递到模板

Django - 将变量从函数视图传递到 html 模板

如何从 Django 视图将变量传递给 SCSS

Django 表单向导 - 将请求传递给视图?

如何将变量从 CLI 程序传递到 Python 视图以更新 Django UI?

如何将参数从我的表单操作传递到视图?姜戈