Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Variable from View to Form Django

Basically i am sending email to user with password and username. I can get the username using self.cleaned_data.get('email'). But the problem is that i dont know how to get password from view which i am setting random password in views. So please help me to get that random password from views.py to forms.py in def send_email

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()
like image 368
Cipher Avatar asked Dec 28 '18 08:12

Cipher


1 Answers

Pass the random password to the form at the time of form initialization and handle that in your UserRegisterForm form by overriding the __init__() method

Try this

# 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 ....
like image 97
JPG Avatar answered Oct 13 '22 17:10

JPG