Login

Register django views

Author:
magik_cypress
Posted:
February 5, 2012
Language:
Python
Version:
1.3
Tags:
django views register
Score:
0 (after 0 ratings)

Register django views

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
from django.http import (Http404, HttpResponseRedirect, HttpResponseNotFound,
                        HttpResponse)
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib import messages
from django.utils.functional import lazy
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect
from django.template import Context, RequestContext
from django.contrib.auth.decorators import login_required
from datetime import datetime, date, timedelta
from django_couchdb_utils.auth.models import User
from lepublicateur.app import RegisterForm, UserForm, ResetpwdForm, ChangepwdForm
from lepublicateur.views.utils import sender, template_sender
from lepublicateur.context_processors import *
import sys, os, subprocess, socket, uuid

from django.utils.translation import gettext_lazy as _

def _lookup_template(name):
    return 'lepublicateur/%s.html' % name  

def _device_template(name):
    if name:
        return '%s.html' % name
    else:
        return 'base.html'  

@csrf_protect
def register_email(request):
    """Display the register page.
    """
    device_template = _device_template(get_device())

    d = {}
    d.update(csrf(request))
    if 's' in request.POST:
        csrf_token = request.COOKIES['csrf_token']
        if csrf_token == "":
            # Fall back to X-CSRFToken, to make things easier for AJAX
            request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')  
        else:
            request_csrf_token = csrf_token

        if request_csrf_token != csrf_token:
            return HttpResponseRedirect('start') 

    # Use correct entry type Document class
    entry_type = User
    # Select correct form for entry
    form_class = RegisterForm    

    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            entry = entry_type(**form.cleaned_data)
            uuidd = unicode(uuid.uuid4())
            entry['password'] = entry_type.gen_password(entry['password'])
            entry['uuid'] = uuidd
            entry['is_active'] = False
            # Save the entry to the DB
            entry.save()
            messages.info(request, _('Welcome !'))  
        else:
            messages.error(request, _('Error, no register'))               
        return HttpResponseRedirect('/register-account/%s%s/' % (get_device(), ".html"))        
    else:
        form = RegisterForm()

    context = {
        'form': form,
        'device_template': device_template
    }
    return render_to_response(_lookup_template('register_email'), context,
                              context_instance=RequestContext(request))                              

@csrf_protect
def register_you(request, uuid):
    """Display the register page.
    """
    # Use correct entry type Document class
    entry_type = User
    # Select correct form for entry
    form_class = UserForm    

    if request.method == 'POST':

        try:
            param = {'key': uuid }        
        except:
            raise Http404        

        try:  
            entry = User.get_user_by_uuid(uuid)         
        except IndexError:
            raise Http404

        form = form_class(request.POST)
        if form.is_valid():
            data = entry_type(**form.cleaned_data)
            entry['username'] = data['username']
            entry['first_name'] = data['first_name']
            entry['last_name'] = data['last_name']
            entry['uuid'] = unicode(entry.uuid)       
            password = entry_type.gen_password(data['password'])
            if password:
                entry['password'] = unicode(password)
                entry['is_active'] = True

            # Save the entry to the DB           
            entry.save()
            entry.has_usable_password()
            messages.info(request, _('Welcome !'))  
        else:
            messages.error(request, _('Error, no register'))               
        return HttpResponseRedirect(reverse('log-in'))
    else:
        form = UserForm()

    context = {
        'form': form,
    }
    return render_to_response(_lookup_template('register_you'), context,
                              context_instance=RequestContext(request))

@csrf_protect
def activate_account(request):
    """Display the register page.
    """
    if request.method == 'POST':
        email = request.POST['email']
        entry_type = User
        entry = entry_type.get_user_by_email(email)
        entry['is_active'] = True
        entry.save()

    title = _('Activate your account')
    context = {
        'title': title
    }
    return render_to_response(_lookup_template('email/thanks_register'), context,
                              context_instance=RequestContext(request))                               

@csrf_protect
def register_confirm(request):
    """Active invitation.
    """
    if request.method == 'POST':     

        try:  
            entry_id = request.POST['entry_id']
            entry = User.get_user_by_uuid(entry_id)         
        except IndexError:
            raise Http404

        if entry:
            entry['is_active'] = True
            entry.save()
            messages.info(request, _('Register confirm is correct'))                

        
            template_sender(
                        entry, entry['email'], 
                        _(u'[Mariage] : Your account is activated'), 
                        'lepublicateur/email/activate_register.txt', 
                        'lepublicateur/email/activate_register.html')

            template_sender(
                        entry, settings.DEFAULT_FROM_EMAIL, 
                        _(u'[Mariage] : New register'), 
                        'lepublicateur/email/notifiation_admin_register.txt', 
                        'lepublicateur/email/notifiation_admin_register.html')                    

        else:
            messages.error(request, _('Error, Register confirm not is correct'))   
        # # Get beautiful template 
        # plaintext = get_template('lepublicateur/email/activate_register.txt')
        # htmly     = get_template('lepublicateur/email/activate_register.html')
        # # get current url
        # current_path = get_full_domaine(settings.DOMAINNAME)
        # uuidd = unicode(uuid.uuid4())
        # context = Context({ 'email': entry['email'], 'username': entry['username'], 
        #                     'first_name': entry['first_name'],
        #                     'last_name': entry['last_name'], 'current_path': current_path })                
        # subject = _(u'[Mariage] : Your account is activated')
        # to_email = entry['email']
        # sender(subject, context, settings.DEFAULT_FROM_EMAIL, to_email, plaintext, htmly)
        # #messages.success(request, 'success test')

    return HttpResponseRedirect(reverse('list-users'))


@login_required
@csrf_protect
def register_admin(request):
    """Display the register page.
    """
    d = {}
    d.update(csrf(request))
    if 's' in request.POST:
        csrf_token = request.COOKIES['csrf_token']
        if csrf_token == "":
            # Fall back to X-CSRFToken, to make things easier for AJAX
            request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')  
        else:
            request_csrf_token = csrf_token

        if request_csrf_token != csrf_token:
            return HttpResponseRedirect('start') 

    # Use correct entry type Document class
    entry_type = User
    # Select correct form for entry
    form_class = UserForm    

    if request.method == 'POST':       
        form = form_class(request.POST)
        if form.is_valid():
            entries = entry_type(**form.cleaned_data)
            uuidd = unicode(uuid.uuid4())            
            username = request.POST['username']        
            password = entry_type.gen_password(entries['password'])
            email = request.POST['email']

            if password and uuidd and email:
                entries['username'] = unicode(username)
                entries['email'] = unicode(email)
                entries['uuid'] = unicode(uuidd)
                entries['password'] = unicode(password)
                entries['is_active'] = True

                # Save the entry to the DB          
                entries.save()
                entries.has_usable_password()
                messages.info(request, _('Insert user is correct'))  
            else:
                messages.error(request, _('Error, Insert user is not correct'))                
            return HttpResponseRedirect(reverse('list-users'))
    else:
        # Add email for register
        register = RegisterForm()

    context = {
        'register': register
    }
    return render_to_response(_lookup_template('register_admin'), context,
                              context_instance=RequestContext(request))    

@csrf_protect
def reset_password(request):
    """Display the reset password page.
    """
    d = {}
    d.update(csrf(request))
    if 's' in request.POST:
        csrf_token = request.COOKIES['csrf_token']
        if csrf_token == "":
            # Fall back to X-CSRFToken, to make things easier for AJAX
            request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')  
        else:
            request_csrf_token = csrf_token

        if request_csrf_token != csrf_token:
            return HttpResponseRedirect('start') 

    # Use correct entry type Document class
    entry_type = User
    # Select correct form for entry
    form_class = ResetpwdForm    

    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            data = entry_type(**form.cleaned_data)  
            try:
                entry = entry_type.get_user_by_email(data['email'])
                if entry != None:
                    if entry['email'] == data['email']:
                        template_sender(
                                    entry, settings.DEFAULT_FROM_EMAIL, 
                                    _(u'[Mariage] : Reset password'), 
                                    'lepublicateur/email/reset_password.txt', 
                                    'lepublicateur/email/reset_password.html') 

                        messages.info(request, _('Reset password is correct'))  
                    else:
                        messages.error(request, _('Error, Reset password is not correct'))  
                else:
                    messages.error(request, _('Error, Reset password is not correct'))                      
            except IndexError:
                raise Http404
                                
            return HttpResponseRedirect(reverse('log-in'))
    else:
        form = form_class()

    context = {
        'form': form,
    }
    return render_to_response(_lookup_template('reset_password'), context,
                              context_instance=RequestContext(request))    

@csrf_protect
def change_password(request, uuid):
    """Display the reset password page.
    """
    d = {}
    d.update(csrf(request))
    if 's' in request.POST:
        csrf_token = request.COOKIES['csrf_token']
        if csrf_token == "":
            # Fall back to X-CSRFToken, to make things easier for AJAX
            request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')  
        else:
            request_csrf_token = csrf_token

        if request_csrf_token != csrf_token:
            return HttpResponseRedirect('start') 

    # Use correct entry type Document class
    entry_type = User
    # Select correct form for entry
    form_class = ChangepwdForm    

    if request.method == 'POST':       

        form = form_class(request.POST)
        if form.is_valid():
            data = entry_type(**form.cleaned_data)  
            try:
                entry = entry_type.get_user(request.POST['username'])  
            except IndexError:
                raise Http404
           
            if data['password'] == data['confirm_password']:
                password = entry_type.gen_password(data['password'])
                if password:
                    entry['password'] = unicode(password)
                  
                    # Save the entry to the DB          
                    entry.save()
                    entry.has_usable_password()
                    messages.info(request, _('Change password is correct'))  
                else:
                    messages.error(request, _('Error, Change password is not correct'))             

            return HttpResponseRedirect(reverse('log-in'))
    else:
        if request.method == 'GET':
            try:
                entry = entry_type.get_user_by_uuid(uuid)
                if entry:
                    form = form_class()
                    messages.info(request, _('Change password is correct'))  
                else:
                    messages.error(request, _('Error, Change password is not correct'))  
            except IndexError:
                raise Http404                

    context = {
        'entry': entry,
        'form': form,
    }
    return render_to_response(_lookup_template('change_password'), context,
                              context_instance=RequestContext(request))                                

More like this

  1. Django admin autoregister by Mimino 1 year, 8 months ago
  2. Anonymous required decorator by Motanelu 5 years, 6 months ago
  3. Django-admin autoregister -- automatic model registration by Samus_ 5 years, 1 month ago
  4. One register on admin by zodman 3 years, 5 months ago
  5. Using dojo/json to check for username availability by heckj 8 years, 1 month ago

Comments

Please login first before commenting.