cola
cola

Reputation: 12466

Can't get the password input field in template using ModelForm

models.py:

class Users(models.Model):
    username = models.CharField(max_length=255)
    slug = models.CharField(max_length=255, default='0')
    password = models.CharField(max_length=300)
    password_token = models.CharField(max_length=300, default='0')
    email = models.CharField(max_length=255)
    email_verified = models.BooleanField(default=False)
    email_token = models.CharField(max_length=255)
    email_token_expiry = models.DateTimeField()
    tos = models.BooleanField(default=False)
    active = models.BooleanField(default=False)
    last_login = models.DateTimeField(auto_now_add=True)
    last_action = models.DateTimeField(auto_now_add=True)
    is_admin = models.BooleanField(default=False)
    role = models.CharField(max_length=255, default='0')
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.username

class UsersModelForm(forms.ModelForm):
    passwordrepeat = forms.PasswordInput()

    class Meta:
        model = Users
        fields = ('username', 'password', 'email')
        widgets = {
            'password' : forms.PasswordInput(),
        }

    def clean(self):
        cleaned_data = self.cleaned_data
        password = cleaned_data.get("password")
        passwordrepeat = cleaned_data.get("passwordrepeat")
        if password != passwordrepeat:
            raise forms.ValidationError("Passwords must match.")

        return cleaned_data

In template I get

username
password
email

I can't get the passwordrepeat input field in template. And how can I set the label for 'passwordrepeat' field. The label would be Repeat Password

And can I omit the def clean from UsersModelForm. I want to compare password and repeatpassword in views.py not in models.py.

views.py:

def register(request):
    flag = True
    possible = '0123456789abcdefghijklmnopqrstuvwxyz'
    token = ''
    tempToken = ''

    current_datetime = datetime.datetime.now()

    user = UsersModelForm()
    if request.method == 'POST':
        userf = UsersModelForm(request.POST)
        username = userf.data['username']
        password = userf.data['password']
        passwordrepeat = userf.data['passwordrepeat']
        email = userf.data['email']

        tempSalt = bcrypt.gensalt()
        password = bcrypt.hashpw(password,tempSalt)
        passwordrepeat = bcrypt.hashpw(passwordrepeat,tempSalt)

        if password != passwordrepeat:
            flag = False
            passVariable = {'user':user, 'flag': False}
            return render_to_response('register.html', passVariable, context_instance=RequestContext(request))

        elif password == passwordrepeat:
            for i in range(1,10):
                temp = random.choice(possible)
                token = token + temp

            if userf.is_valid():
                check = userf.save(commit=False)
                check.email_token = token
                check.email_token_expiry = current_datetime + timedelta(1)
                check.password = password
                check.passwordrepeat = passwordrepeat
                check.save()
                subject, from_email, to = 'hello', '[email protected]', '[email protected]'
                text_content = 'This is an important message.'
                html_content = '<a href="http://127.0.0.1:8000/confirm/' + token + '">Click this link to confirm email</a>'
                msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
                msg.attach_alternative(html_content, "text/html")
                msg.send()
                return HttpResponseRedirect('/')
    else:
        return render_to_response('register.html', {"user": user, 'flag': True}, context_instance=RequestContext(request))

Upvotes: 0

Views: 729

Answers (1)

DrTyrsa
DrTyrsa

Reputation: 31951

Right answer: use django-registration. And django built-in auth system. Don't reinvent the wheel.

Answer to your question: you don't see passwordrepeat because forms.PasswordInput is not a field, it's a widget. Widget can't be rendered without a field. You should use CharField with PasswordInput here. If you want to set label, set it, label argument looks good for this task.

passwordrepeat = forms.CharField(widget=forms.PasswordInput, label=u'Repeat Password')

The form

class UsersModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UsersModelForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder = ['username', 'password', 'passwordrepeat', 'email']

    # ... other fields and methods ...

Upvotes: 5

Related Questions