Exemplo n.º 1
0
def create_user(request):
    context = {}
    context_instance = RequestContext(request)
    form = UserCreateForm(request.POST or None)
    context['form'] = form
    
    if request.user.is_authenticated():
        return redirect('/user/dashboard')

    if request.method == 'POST' and form.is_valid():
        first_name = form.cleaned_data['first_name']
        last_name = form.cleaned_data['last_name']
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        phone = form.cleaned_data['phone']
        try:
            users_manager.create_user(first_name, last_name, username, password, email, phone)
            # authenticate and login
            user = authenticate(username=username, password=password)
            login_auth(request, user)
            return redirect('/user/dashboard')
        except Exception as exc:
            # 400
            form.errors['__all__'] = form.error_class(["Error: %s" % exc.message])

    # GET / POST with invalid input
    return render_to_response('user/create.html', context, context_instance=context_instance)
Exemplo n.º 2
0
def register(request):
	context = {}
	context["news"] = get_news_by_request(request)
	user = User()
	if request.method == 'POST':
		form = UserCreateForm(request.POST, instance = user)
		if form.is_valid():
			pw = user.password
			user.set_password(user.password)
			user.theme_id=4
			user.input_type_id=1
			if not open_registration:
				user.is_active = False
			form.save()
			ro = ReminderOffsets.objects.get(value=0)
			user.reminder_offset.add(ro)
			ro = ReminderOffsets.objects.get(value=2)
			user.reminder_offset.add(ro)
			if open_registration:
				group = Group.objects.filter(name="BuLiTipp")[0]
				user.groups.add(group)
				user = authenticate(username=user.username, password=pw)
				djlogin(request, user)
				messages.success(request, "Benutzer erfolgreich angelegt! Tritt als nächstes einer Tippgemeinschaft bei!")
				return HttpResponseRedirect(reverse("user", args=["tgchange"]))
			else:
				mail.send("BuLiTipp: User registriert", "*****@*****.**", "Bitte administriere den neuen User " + user.username+ " !")
				messages.success(request, "Benutzer erfolgreich angelegt! Du kannst dich einloggen sobald der Administrator dich freigeschaltet hat.")
				return HttpResponseRedirect(reverse("home"))
			
	else:
		form = UserCreateForm(instance=user)
	context["form"] = form
	return render(request, 'registration/register.html', context)
Exemplo n.º 3
0
def signup():
    form = UserCreateForm()
    if request.method == 'POST' and form.validate_on_submit():
        request_data = {
            'group': form.group.data,
            'name': form.name.data,
            'email': form.email.data,
            'password': generate_password_hash(form.password1.data)
        }
        collection = db['users']
        user_data = collection.find_one(
            filter={'email': request_data['email']})
        if user_data:
            flash('이미 존재하는 사용자입니다.')
        else:
            user_data = collection.find_one(
                filter={'group': request_data['group']})
            request_data['admin'] = False
            if user_data is None:
                request_data['admin'] = True
            user_data = collection.find_one(sort=[('create_time', -1)])
            if user_data:
                user_id = user_data['user_id'] + 1
            else:
                user_id = 1
            request_data['create_time'] = str(datetime.now())
            request_data['user_id'] = user_id
            collection.insert(request_data)
            return redirect(url_for('main.index'))
    return render_template('/signup.html', form=form)
Exemplo n.º 4
0
def signup(request):
    """
    User registration view.
    """
    auth_form = AuthenticateForm()

    if request.method == 'POST':
        form = UserCreateForm(data=request.POST)
        if form.is_valid():
            form.save()
            user = authenticate(email=request.POST['email'], password=request.POST['password2'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('/')

        else:
            return render_to_response('home.html', {
                'auth_form': auth_form, 'user_form': form, 
            }, context_instance=RequestContext(request))

    elif request.method == 'GET':
        form = UserCreateForm()
        return render_to_response('home.html', {
            'auth_form': auth_form, 'user_form': form, 
        }, context_instance=RequestContext(request))
Exemplo n.º 5
0
def customregister(request):
    returnJson = ifReturnJson(request)
    data_dict = {}
    data_dict['type'] = 'register'
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            new_user = form.save()

            data_dict['success'] = 1
            data_dict['uid'] = new_user.id
            data_dict['username'] = new_user.username
            data_dict['name'] = new_user.first_name + new_user.last_name
            data_dict['email'] = new_user.email

            #Redirect to the registration complete page
            #return HttpResponseRedirect("/homepage/")
        else:
            data_dict['success'] = 0
            #invalid form
            data_dict['error_message'] = 'invalid registration form'
        if returnJson == 1:
            return HttpResponse(json.dumps(data_dict),content_type='application/json')
        elif returnJson == 0:
            return redirect('/accounts/register')
    else:
        form = UserCreateForm()
        return render(request, "registration/registration_form.html", {
            'form': form,
        })
Exemplo n.º 6
0
def create(request):
    form = UserCreateForm(request.POST or None)
    if form.is_valid():
        form.save()
    context = {
        "forms": form,
    }
    return render(request,"home.html",context)
Exemplo n.º 7
0
	def create_user(self, version = 0):
		"""
		Creates a UserProfile. Version is an integer that determines which userprofile to generate (one of two)
		"""
		registration_values = self.create_valid_user_vals(version)
		user_form = UserCreateForm(registration_values)
		if user_form.is_valid():
			return user_form.save()
Exemplo n.º 8
0
    def create_user(self, version=0):
        """
		Creates a UserProfile. Version is an integer that determines which userprofile to generate (one of two)
		"""
        registration_values = self.create_valid_user_vals(version)
        user_form = UserCreateForm(registration_values)
        if user_form.is_valid():
            return user_form.save()
Exemplo n.º 9
0
def create_account(request):
    if request.method == "POST":
        form = UserCreateForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/success/')
    else:
        form = UserCreateForm()
    return render(request,'create.html',{'form':form})
Exemplo n.º 10
0
def register(request):
    if request.method == "POST":
        form = UserCreateForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/videos/")
    else:
        form = UserCreateForm()
    return render(request, "registration/register.html", {"form": form})
Exemplo n.º 11
0
    def post(self):
        form = UserCreateForm()
        if not form.validate_on_submit():
            return form.errors, 422

        user = User(form.email.data, form.password.data)
        db.session.add(user)
        db.session.commit()
        return UserSerializer(user).data
Exemplo n.º 12
0
def new_user(request):
    if request.method=='POST':
        formulario = UserCreateForm(request.POST)
        if formulario.is_valid:
            formulario.save()
            return HttpResponseRedirect('/')
    else:
        formulario = UserCreateForm()
    return render_to_response('new_user.html',{'formulario':formulario},context_instance=RequestContext(request))
Exemplo n.º 13
0
def register(request):
    register_success = reverse('user_register_success')
    if request.method == 'POST':
		form = UserCreateForm(request.POST)
		if form.is_valid():
			form.save()
			return HttpResponseRedirect(register_success)
    else:
		form = UserCreateForm()
    return render_to_response('newaccounts/registration.html', {'form':form}, context_instance=RequestContext(request))
Exemplo n.º 14
0
def signup(request, template_name="authentication/signup.html"):
    form = UserCreateForm(request.POST or None)

    if request.POST:
        if form.is_valid():
            form.save()

            return HttpResponseRedirect(reverse("home"))

    return render(request, template_name, {"form": form})
Exemplo n.º 15
0
def create_user(request):
    """Creates a new user"""
    if request.method == "POST":
        form = UserCreateForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = UserCreateForm()
    return render(request, 'quiz/create_user.html', context={'form': form})
Exemplo n.º 16
0
def register(request):
    if request.user.is_authenticated():
        
        return redirect('/')

    if request.method == 'POST':
        user_information = {
        'username': request.POST['username'],
        'password1': request.POST['password1'],
        'password2': request.POST['password2'],
        'last_name': request.POST['last_name'],
        'city': request.POST['city'],
        'first_name': request.POST['first_name'],
        'state': request.POST['state'],
        'middle_initial': request.POST['middle_initial'],
        'birth_date': request.POST['birth_date'],
        'email': request.POST['email'],
        'street_address': request.POST['street_address'],
        'zip_code': request.POST['zip_code']
        }

        form = UserCreateForm(user_information)
        if form.is_valid():
           
            form.save()
            return redirect('/') 
        else: 
            form_errors = form.errors
            return render_to_response('register.html', {'errors': form_errors, 'form': form}, context_instance=RequestContext(request))
    else: #AJAX form validation
        request_copy = request.GET.copy()
      

        if 'username' in request_copy: #Username in use?
            name = request_copy['username']
            response_data = {}

            if UserProfile.objects.filter(username__iexact=name): 
                response_data['result'] = 'false'
            else:           
                response_data['result'] = 'true'
            return HttpResponse(response_data['result'], content_type='text/plain')
          
            # return HttpResponse(json.dumps(response_data), content_type = "application/json")
        if 'email' in request_copy: #Email in use?
            entered_email = request_copy['email']
            response_data = {}
            if UserProfile.objects.filter(email__iexact=entered_email):
                response_data['result'] = 'false'
            else:
               response_data['result'] = 'true'
            return HttpResponse(response_data['result'], content_type = 'text/plain')
        else:
            form = UserCreateForm()
            return render_to_response("register.html", {'form': form, 'errors':form.errors}, context_instance=RequestContext(request))
Exemplo n.º 17
0
def settings(request):
    tweet_form = TweetForm()
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
        else:
            return render(request, 'settings.html', {'form': form,})
    form = UserCreateForm(instance=request.user)
    return render(request, 'settings.html', {'form': form, 'tweet_form': tweet_form})
Exemplo n.º 18
0
def registration(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/portal/")
    else:
        form = UserCreateForm()
    return render(request, "registration/register.html", {
        'form': form,
    })
Exemplo n.º 19
0
def register(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/importinfo/")
    else:
        form = UserCreateForm()
    return render_to_response("registration/register.html", {
        'form': form,
    }, context_instance=RequestContext(request))
Exemplo n.º 20
0
	def post(self, request):
		form = UserCreateForm(request.POST)
		if form.is_valid():
			form.save()
			request.session["temp_user"] = {
				'username': request.POST["username"],
				'new': True,
			}
			return redirect('/accounts/register/done/')
		else:
			return render(request, self.template_name, {'user_create_form': form})
Exemplo n.º 21
0
def create_account(request):
    if request.method == "POST":
        form = UserCreateForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            p = UserProfile(user=new_user)
            p.save()
            return HttpResponseRedirect("/create-account/success")
    else:
        form = UserCreateForm()

    return render(request, "homepage/create-account.html", {"form": form})
Exemplo n.º 22
0
def signup(request, template_name="registration/signup.html"):
    if request.user.is_authenticated():
        messages.warning(request, 'Logout to create a new user')
        return redirect('/')
    else:
        form = UserCreateForm(request.POST or None)
        if form.is_valid():
            form.save()
            messages.success(request,
                             'User Account Created. Please proceed to login.')
            return redirect('/login/')
        return render(request, template_name, {'form': form})
Exemplo n.º 23
0
Arquivo: views.py Projeto: ChenAri/BAL
def register(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        password = request.POST.get('password')
	if password == 'bal423kp':
            if form.is_valid():
            	user = form.save()
                return HttpResponseRedirect('/account/login')
	else:
	    return HttpResponseRedirect('/account/register')
    else:
        form = UserCreateForm()
    return render_to_response('register.html',RequestContext(request,locals()))
Exemplo n.º 24
0
def inbox_team_add(request, slug):
    inbox = get_object_or_404(Inbox, slug=slug)
    user_form = UserCreateForm(request.POST or None, inbox=inbox)
    if request.method == "POST" and user_form.is_valid():
        member = user_form.save()
        inbox.users.add(member)
        return redirect('inbox-mails-list', inbox.slug)
    context = {
        "inbox": inbox,
        "user_form": user_form,
    }
    forward_formset = ForwardRuleFormSet(instance=inbox, prefix='forward_rule')
    context.update({"forward_formset": forward_formset, })
    return render(request, 'inbox/list.html', context)
Exemplo n.º 25
0
def reg(request):
    create_form = UserCreateForm(request.GET)
    if create_form.is_valid():
        user = create_form.save()
        profile = UserProfile()
        if request.GET.get("man") == "True":
            profile.man = True
        else:
            profile.man = False
        profile.user_id = user.id
        profile.save()
        return HttpResponse("create user: "******"user is not created")
Exemplo n.º 26
0
def register_user(request):

    template_name = 'kitchen/crispy.html'

    if request.method == 'POST':
        user_form = UserCreateForm(request.POST)
        if user_form.is_valid():
            username = user_form.clean_username()
            password = user_form.clean_password2()
            user_form.save()

            user = authenticate(username=username, password=password)
            if user:
                # save extra parameters - email
                user.email = user_form.data['email']
                user.save()
                #ASK - may be we should init it only in one place - on login?
                initUser(user)
                login(request, user)
                return redirect('account-list')
        return render(request, template_name, {'form': user_form})
    args = {}
    args.update(csrf(request))
    args['form'] = UserCreateForm()
    print args
    return render(request, template_name, args)
Exemplo n.º 27
0
def index():

    form = UserCreateForm()

    if form.validate_on_submit():

        if not form.validate_on_submit():
            return form.errors, 422

        user = User(form.email.data, form.password.data)
        db.session.add(user)
        db.session.commit()

    return render_template('index.html', form=form)
Exemplo n.º 28
0
def sign_up(request):
    if request.user.is_authenticated():
        return redirect('app_events')

    form = UserCreateForm(data=request.POST.copy() or None)

    if form.is_bound and form.is_valid() and form.save():
        messages.success(request, _(u'Thank you for registering. You are now logged in.')) 
        login(request, authenticate(
            username=request.POST['username'],
            password=request.POST['password1'])
        )
        return redirect('app_events')

    return direct_to_template(request, 'auth/sign_up.html', {'form': form})
Exemplo n.º 29
0
def registro(request):
    if request.method == 'POST':
        formulario = UserCreateForm(request.POST)
        if formulario.is_valid:
            formulario.save()
            u = User.objects.get(username=request.POST['username'])
            u.is_active=False
            u.save()
            usuario = Usuarios(usuario=u)
            usuario.save()
            return HttpResponseRedirect('/usuario/editar/')
    else:
        formulario = UserCreateForm()
    context={"formulario":formulario}
    return render_to_response('usuario/registro.html', context, context_instance=RequestContext(request))
Exemplo n.º 30
0
def sign_up(request):
    if request.user.is_authenticated():
        return redirect('app_events')

    form = UserCreateForm(data=request.POST.copy() or None)

    if form.is_bound and form.is_valid() and form.save():
        messages.success(
            request, _(u'Thank you for registering. You are now logged in.'))
        login(
            request,
            authenticate(username=request.POST['username'],
                         password=request.POST['password1']))
        return redirect('app_events')

    return direct_to_template(request, 'auth/sign_up.html', {'form': form})
Exemplo n.º 31
0
def register(request):
	if len(request.POST) > 0:
		form = UserCreateForm(request.POST)
		if form.is_valid():
			user = form.save()
			pwd = form.cleaned_data['password1']
			s_user = authenticate(username=user.username, password=pwd)
			if s_user is not None:
				login(request, s_user)
				return HttpResponseRedirect('preferences')
			else:
				return render_to_response("register.html", {'form': form})
		else:
			return render_to_response("register.html", {'form': form})
	else:
		form = UserCreateForm()
		return render_to_response("register.html", {'form': form})
Exemplo n.º 32
0
def register(request):
	if request.method=='POST':
		form=UserCreateForm(request.POST)
		if form.is_valid():
			u=form.save()
			c=Country.objects.get(user=u)
			b=Build(country=c)
			b.save()
			a=Army(country=c)
			a.save()
			t=Tech(country=c)
			t.save()
			r=Resource(country=c)
			r.save()
			return HttpResponseRedirect('/kotw/')
	else:
		form=UserCreateForm()
	return render_to_response('form.html', {'page_title': title, 'page_css':css, 'register_form':form}, context_instance=RequestContext(request))
Exemplo n.º 33
0
def register(request):
    args = {}
    args.update(csrf(request))
    args['username'] = auth.get_user(request).username
    args['form'] = UserCreateForm()
    if request.POST:
        newuser_form = UserCreateForm(request.POST)
        if newuser_form.is_valid():
            newuser_form.save()
            newuser = auth.authenticate(username=newuser_form.cleaned_data['username'],
                                        password=newuser_form.cleaned_data['password2'],
                                        email=newuser_form.cleaned_data['email'],
                                        first_name=newuser_form.cleaned_data['first_name'],
                                        last_name=newuser_form.cleaned_data['last_name'])
            auth.login(request, newuser)
            return redirect('/')
        else:
            args['form'] = newuser_form
    return render_to_response('registration/register.html', args)
Exemplo n.º 34
0
def create_account(request):
    if request.method == "POST":
        form = UserCreateForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/success/')
    else:
        form = UserCreateForm()
    return render(request, 'create.html', {'form': form})
Exemplo n.º 35
0
def create_user(request):
    if request.POST:
        user_form = UserCreateForm(request.POST)
        if user_form.is_valid():
            username = user_form.clean_username()
            password = user_form.clean_password2()
            user_form.save()
            user = authenticate(username=username, password=password)
            login(request, user)
            request.session["notice"] = "User successfully logged in"
            return HttpResponseRedirect("/")
    else:
        user_form = UserCreateForm()

    return render_to_response('users/create_user.html',
                              {'user_form': user_form},
                              context_instance=RequestContext(request))
Exemplo n.º 36
0
def Register(request):
    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        c_form = UserCreateForm(data=request.POST)

        if user_form.is_valid() and c_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            c = c_form.save(commit=False)
            c.user = user
            c.save()

            c_form.save_m2m()
            registered = True

        else:
            print user_form.errors, c_form.errors

    else:

        user_form = UserForm()
        c_form = UserCreateForm()

    return render(request, 'gadgetapp/register.html',
                  {'user_form': user_form, 'c_form': c_form, 'registered': registered}, RequestContext(request))
Exemplo n.º 37
0
def register_user(request):
    
    template_name = 'kitchen/crispy.html'

    if request.method == 'POST':
        user_form = UserCreateForm(request.POST)
        if user_form.is_valid():
            username = user_form.clean_username()
            password = user_form.clean_password2()
            user_form.save()
            
            user = authenticate(username=username,
                                password=password)
            if user:
                # save extra parameters - email
                user.email = user_form.data['email']
                user.save()
                #ASK - may be we should init it only in one place - on login?
                initUser(user)
                login(request, user)
                return redirect('account-list')
        return render(request,
                      template_name,
                      { 'form' : user_form })
    args = {}
    args.update(csrf(request))
    args['form'] = UserCreateForm()
    print args
    return render(request, template_name, args)
Exemplo n.º 38
0
def nuevo_usuario(request):
    """
    Funcion que recibe un request y devuelve un response para crear un nuevo usuario
    @param request: django.http.HttpRequest.
    @return: render_to_response.
    """
    usuario = request.user
    if not usuario.is_superuser:
        return HttpResponseRedirect('/gestion')
    if request.method == 'POST':
        formulario = UserCreateForm(request.POST)
        if formulario.is_valid:
            try:
                formulario.save()
                return HttpResponseRedirect('/')
            except:
                error = 'Error al procesar la entidad'
                return render_to_response('crear.html', {'formulario': formulario, 'errors': error, 'usuario': usuario},
                                          context_instance=RequestContext(request))
    else:
        formulario = UserCreateForm()
    return render_to_response('crear.html', {'formulario': formulario, 'usuario': usuario},
                              context_instance=RequestContext(request))
Exemplo n.º 39
0
def sign_up(request, user_form=None, incomplete_form=None):

    if request.method == 'POST' and incomplete_form is None:
        user_form = UserCreateForm(data=request.POST)
        if user_form.is_valid():
            max_username = User.objects.all().aggregate(
                Max('username'))['username__max']
            if (max_username != None and max_username != 'admin'):
                temp = 'ID00' + str(int(max_username[2:]) + 1)
            else:
                temp = 'ID001001'
            user_form.cleaned_data['card_no'] = temp
            user_form.cleaned_data['username'] = temp
            password = user_form.clean_password2()
            user_form.save()
            user = authenticate(username=temp, password=password)
            login(request, user)
            return redirect('/')
        else:
            messages.error(request, "Form invalid")
            return sign_up(request, user_form=user_form, incomplete_form=True)
    if incomplete_form is None or not incomplete_form:
        user_form = UserCreateForm()
    return render(request, 'sign_up.html', {'user_form': user_form})
Exemplo n.º 40
0
def register_user(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            user = form.save()
            return HttpResponse("yeah!")

    else:
        form = UserCreateForm()

    return render(request, 'trainer/register.html', {'form': form})
Exemplo n.º 41
0
def registration(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/portal/")
    else:
        form = UserCreateForm()
    return render(request, "registration/register.html", {
        'form': form,
    })
Exemplo n.º 42
0
def create_account(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            p = UserProfile(user=new_user)
            p.save()
            return HttpResponseRedirect('/create-account/success')
    else:
        form = UserCreateForm()

    return render(request, 'homepage/create-account.html', {'form': form})
Exemplo n.º 43
0
def register(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/importinfo/")
    else:
        form = UserCreateForm()
    return render_to_response("registration/register.html", {
        'form': form,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 44
0
def joinus():
    form = UserCreateForm()
    
    if request.method == 'POST':
        user = db.member.find_one({'id': form.userid.data})
        if not user:
            user = {
                'id' : form.userid.data,
                'password' : generate_password_hash(form.password1.data),
                'name': form.name.data,
                'email' : form.email.data,
                'is_student' : form.is_student.data,
                'department' : form.department.data
            }
            print(user)
            db.member.insert_one(user)
            return redirect(url_for('login'))
        else:
            flash('이미 존재하는 사용자입니다')

    return render_template('joinus.html', form=form)
Exemplo n.º 45
0
def register(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            u = form.save()
            c = Country.objects.get(user=u)
            b = Build(country=c)
            b.save()
            a = Army(country=c)
            a.save()
            t = Tech(country=c)
            t.save()
            r = Resource(country=c)
            r.save()
            return HttpResponseRedirect('/kotw/')
    else:
        form = UserCreateForm()
    return render_to_response('form.html', {
        'page_title': title,
        'page_css': css,
        'register_form': form
    },
                              context_instance=RequestContext(request))
Exemplo n.º 46
0
def register(request):
    if request.user.is_authenticated():

        return redirect('/')

    if request.method == 'POST':
        user_information = {
            'username': request.POST['username'],
            'password1': request.POST['password1'],
            'password2': request.POST['password2'],
            'last_name': request.POST['last_name'],
            'city': request.POST['city'],
            'first_name': request.POST['first_name'],
            'state': request.POST['state'],
            'middle_initial': request.POST['middle_initial'],
            'birth_date': request.POST['birth_date'],
            'email': request.POST['email'],
            'street_address': request.POST['street_address'],
            'zip_code': request.POST['zip_code']
        }

        form = UserCreateForm(user_information)
        if form.is_valid():

            form.save()
            return redirect('/')
        else:
            form_errors = form.errors
            return render_to_response('register.html', {
                'errors': form_errors,
                'form': form
            },
                                      context_instance=RequestContext(request))
    else:  #AJAX form validation
        request_copy = request.GET.copy()

        if 'username' in request_copy:  #Username in use?
            name = request_copy['username']
            response_data = {}

            if UserProfile.objects.filter(username__iexact=name):
                response_data['result'] = 'false'
            else:
                response_data['result'] = 'true'
            return HttpResponse(response_data['result'],
                                content_type='text/plain')

            # return HttpResponse(json.dumps(response_data), content_type = "application/json")
        if 'email' in request_copy:  #Email in use?
            entered_email = request_copy['email']
            response_data = {}
            if UserProfile.objects.filter(email__iexact=entered_email):
                response_data['result'] = 'false'
            else:
                response_data['result'] = 'true'
            return HttpResponse(response_data['result'],
                                content_type='text/plain')
        else:
            form = UserCreateForm()
            return render_to_response("register.html", {
                'form': form,
                'errors': form.errors
            },
                                      context_instance=RequestContext(request))
Exemplo n.º 47
0
def user_add(request):
    ad_suffix = GVSIGOL_LDAP['AD']
    if not ad_suffix:
        show_pass_form = True
    else:
        show_pass_form = False

    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            assigned_groups = []

            is_staff = False
            if 'is_staff' in form.data:
                is_staff = True

            is_superuser = False
            if 'is_superuser' in form.data:
                is_superuser = True
                is_staff = True

            assigned_groups = []
            for key in form.data:
                if 'group-' in key:
                    assigned_groups.append(int(key.split('-')[1]))

            try:
                if form.data['password1'] == form.data['password2']:
                    user = User(username=form.data['username'].lower(),
                                first_name=u''.join(
                                    form.data['first_name']).encode('utf-8'),
                                last_name=u''.join(
                                    form.data['last_name']).encode('utf-8'),
                                email=form.data['email'].lower(),
                                is_superuser=is_superuser,
                                is_staff=is_staff)
                    user.set_password(form.data['password1'])
                    user.save()

                    #admin_group = UserGroup.objects.get(name__exact='admin')
                    aux = UserGroup.objects.filter(name="admin")
                    if aux.count() > 1:
                        print "WARNING: table gvsigol_auth_usergroup inconsistent !!!!!!!!!!!"

                    admin_group = aux[0]

                    if user.is_superuser:
                        core_services.ldap_add_user(user,
                                                    form.data['password1'],
                                                    True)
                        core_services.ldap_add_group_member(user, admin_group)
                        usergroup_user = UserGroupUser(user=user,
                                                       user_group=admin_group)
                        usergroup_user.save()

                    else:
                        core_services.ldap_add_user(user,
                                                    form.data['password1'],
                                                    False)
                        #core_services.ldap_add_group_member(user, admin_group)

                    for ag in assigned_groups:
                        user_group = UserGroup.objects.get(id=ag)
                        usergroup_user = UserGroupUser(user=user,
                                                       user_group=user_group)
                        usergroup_user.save()
                        core_services.ldap_add_group_member(user, user_group)

                    #User backend
                    if is_superuser or is_staff:
                        ugroup = UserGroup(
                            name='ug_' + form.data['username'].lower(),
                            description=_(u'User group for') + ': ' +
                            form.data['username'].lower())
                        ugroup.save()

                        ugroup_user = UserGroupUser(user=user,
                                                    user_group=ugroup)
                        ugroup_user.save()

                        core_services.ldap_add_group(ugroup)
                        core_services.add_data_directory(ugroup)
                        core_services.ldap_add_group_member(user, ugroup)

                        url = mapservice_backend.getBaseUrl() + '/'
                        ws_name = 'ws_' + form.data['username'].lower()

                        if mapservice_backend.createWorkspace(
                                ws_name, url + ws_name, '',
                                url + ws_name + '/wms', url + ws_name + '/wfs',
                                url + ws_name + '/wcs',
                                url + 'gwc/service/wms'):

                            # save it on DB if successfully created
                            newWs = Workspace(
                                name=ws_name,
                                description='',
                                uri=url + ws_name,
                                wms_endpoint=url + ws_name + '/wms',
                                wfs_endpoint=url + ws_name + '/wfs',
                                wcs_endpoint=url + ws_name + '/wcs',
                                cache_endpoint=url + 'gwc/service/wms',
                                created_by=user.username,
                                is_public=False)
                            newWs.save()

                            ds_name = 'ds_' + form.data['username'].lower()
                            services_utils.create_datastore(
                                request, user.username, ds_name, newWs)

                            mapservice_backend.reload_nodes()

                    auth_utils.sendMail(user, form.data['password1'])

                    return redirect('user_list')

            except Exception as e:
                print "ERROR: Problem creating user " + str(e)
                errors = []
                #errors.append({'message': _("The username already exists")})
                groups = auth_utils.get_all_groups()
                return render_to_response(
                    'user_add.html', {
                        'form': form,
                        'groups': groups,
                        'errors': errors,
                        'show_pass_form': show_pass_form
                    },
                    context_instance=RequestContext(request))

        else:
            groups = auth_utils.get_all_groups()
            return render_to_response('user_add.html', {
                'form': form,
                'groups': groups,
                'show_pass_form': show_pass_form
            },
                                      context_instance=RequestContext(request))

    else:

        form = UserCreateForm()
        groups = auth_utils.get_all_groups()
        return render_to_response('user_add.html', {
            'form': form,
            'groups': groups,
            'show_pass_form': show_pass_form
        },
                                  context_instance=RequestContext(request))
Exemplo n.º 48
0
 def test_form_should_validate_correctly(self):
     self.assertFalse(UserCreateForm(self.invalid_user).is_valid())
     self.assertTrue(UserCreateForm(self.valid_user).is_valid())