0

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))
2
  • Could you dpaste the corresponding view? Commented Jan 17, 2012 at 10:07
  • I updated the original post. See that again to understand. Commented Jan 17, 2012 at 13:39

1 Answer 1

5

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 ...
Sign up to request clarification or add additional context in comments.

12 Comments

Yes, i got the passwordrepeat field now, but the sequence of the fiedls are 1)username 2)password 3)email 4)passwordrepeat. How can i make the sequence in this format? 1)username 2)password 3)passwordrepeat 4)email
@guru self.fields.keyOrder = ['username', 'password', 'passwordrepeat', 'email']. Place it in overrided __init__
Where to add this line? self.fields.keyOrder = ['username', 'password', 'passwordrepeat', 'email'] ?
And can i omit the def clean: method? I updated the original post. See that again to understand.
@guru Place it in form's overrided __init__ as I said a comment before. :-) You can omit clean method, but why? It's a good pace for logic like that. And your view is a typical example of fat controller antipattern. It's much better to avoid it (that's why it's called antipattern :-))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.