def save_profile(backend, user, response, *args, **kwargs): data = {} data['is_social'] = True if backend.name == 'facebook': if kwargs['is_new']: data['first_name'] = kwargs['details']['first_name'] data['last_name'] = kwargs['details']['last_name'] data['email'] = kwargs['details']['email'] register_form = SocialForm(data=data) if register_form.is_valid(): new_user_instance = User.objects.filter(email=kwargs['details']['email']) if not new_user_instance: new_user_instance = User() new_user_instance.first_name = kwargs['details']['first_name'] new_user_instance.email = kwargs['details']['email'] new_user_instance.last_name = kwargs['details']['last_name'] new_user_instance.profile_status = 1 new_user_instance.save() else: new_user_instance = User.objects.get(email=kwargs['details']['email']) return { 'is_new': True, 'user': new_user_instance } else: backend.strategy.session_set('social_data', data) return HttpResponseRedirect('/registration/') elif backend.name == 'google-oauth2': if kwargs['is_new']: data['first_name'] = kwargs['details']['first_name'] data['last_name'] = kwargs['details']['last_name'] data['email'] = kwargs['details']['email'] register_form = SocialForm(data=data) if register_form.is_valid(): new_user_instance = User.objects.filter(email=kwargs['details']['email']) if not new_user_instance: new_user_instance = User() new_user_instance.first_name = kwargs['details']['first_name'] new_user_instance.email = kwargs['details']['email'] new_user_instance.last_name = kwargs['details']['last_name'] new_user_instance.profile_status = 1 new_user_instance.save() else: new_user_instance = User.objects.get(email=kwargs['details']['email']) return { 'is_new': True, 'user': new_user_instance } else: backend.strategy.session_set('social_data', data) return HttpResponseRedirect('/registration/')
def test_duplicate_email_check(self): user = User() user.username = "******" user.email = "*****@*****.**" user.set_password("test") user.full_clean() user.save() with self.assertRaises(ValidationError): user2 = User() user2.username = "******" user2.email = "*****@*****.**" user2.set_password("test") user2.full_clean() user2.save()
def authenticate(self, token): response_profile = requests.get( 'https://graph.facebook.com/me/', params={ 'access_token': token, } ) facebook_profile = response_profile.json() if 'error' in facebook_profile: return None try: user = User.objects.get(facebook_id=facebook_profile.get('id')) except User.DoesNotExist: user = User(facebook_id=facebook_profile.get('id')) if facebook_profile.get('id') in settings.FACEBOOK_ADMINS: user.is_staff = True user.is_superuser = True user.username = facebook_profile.get('id') user.set_unusable_password() user.facebook_access_token = token user.email = facebook_profile.get('email', '') user.first_name = facebook_profile.get('first_name') user.last_name = facebook_profile.get('last_name') user.save() return user
def create_user(username=None, email=None, password=None): u = User() u.username = username u.email = email u.set_password(password) u.save() return True
def create(self, *args, **kwargs): serializer = self.serializer_class(data=self.request.data) serializer.is_valid(raise_exception=True) username = serializer.data.get('username') phone = serializer.data.get('phone') email = serializer.data.get('email') dob = serializer.data.get('dob') gender = serializer.data.get('gender') image = serializer.validated_data.get('userImage') user = User() user.set_password(serializer.data.get('password')) user.email = email user.username = username user.phone = phone user.userImage = image user.gender = gender user.dob = dob # ut.confirmation_email(email, user) user.save() token, created = Token.objects.get_or_create(user=user) return Response(data={ 'status': status.HTTP_200_OK, 'token': token.key }, status=status.HTTP_200_OK)
def create_user(): try: username = raw_input("Username: "******"Email: ").strip() while True: password = getpass("Password: "******" (confirm): ") if password_confirm == password: break else: print("Passwords do not match... Try again...") u = User(username=username) u.email = email # check for org org = Organization.get_by_name("default") if not org: org = Organization() org.name = "default" org.owner = u.uuid org.save() u.organization = Organization.get_by_name("default").uuid u.set_password(password) u.add_role("admin") u.save() print("User created/updated successfully...") except KeyboardInterrupt: pass
def create_user(request): if not request.method == 'POST': return HttpResponseNotAllowed(['POST']) post_params = json.loads(request.body) form = UserRegistrationForm(data=post_params) if form.is_valid(): user = User() user.email = form.cleaned_data.get('email') user.set_password(form.cleaned_data.get('password')) with transaction.atomic(): user.save() token = Token.create_token() user.token_set.add(token) logger.info("New user created. Email: %s", user.email) user_dict = user.to_dict() user_dict['access_token'] = token.token data = json.dumps(user_dict) return HttpResponse(data) else: logger.error("Invalid form to create new user. Errors: %s", form.errors) data = json.dumps(form.errors) return HttpResponseBadRequest(data)
def register(request): if request.session.get('is_login'): return HttpResponseRedirect(reverse('miunottingham:main_page')) if request.method == "POST": regform = RegisterForm(request.POST) if regform.is_valid(): username = regform.cleaned_data['username'] password1 = regform.cleaned_data['password1'] password2 = regform.cleaned_data['password2'] email = regform.cleaned_data['email'] if User.objects.filter(username=username): message = 'username already exists' return render(request, 'accounts/register.html', locals()) else: if User.objects.filter(email=email): message = 'email address already exists' return render(request, 'accounts/register.html', locals()) else: if password1 != password2: message = 'password does not match' return render(request, 'accounts/register.html', locals()) new_user = User() new_user.username = username # encrypt password new_user.password = hash_code(password2) new_user.email = email new_user.has_confirmed = True new_user.save() return HttpResponseRedirect(reverse('accounts:login_test')) regform = RegisterForm() return render(request, 'accounts/register.html', locals())
def student_create(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) major = Major.objects.get(name=body['major']) level = Level.objects.get(level=body['level']) modeOfEntry = ModeOfEntry.objects.get(name=body['modeOfEntry']) dateBirth = body['dateBirth'] user = User() user.username = body['username'] user.password = dateBirth user.first_name = body['first_name'] user.last_name = body['last_name'] user.email = body['email'] user.type = '7' user.sex = body['sex'] user.save() student = Student() student.user = user student.major = major student.level = level student.modeOfEntry = modeOfEntry student.status = '1' student.dateBirth = dateBirth student.save() serial = StudentSerializer(student) return JsonResponse(serial.data, safe=False, status=200)
def post(self, request): form = RegistrationForm(data=request.POST) response = HttpResponseRedirect('/') if form.is_valid(): user = User() year = request.POST['birthdate_year'] month = request.POST['birthdate_month'] day = request.POST['birthdate_day'] date_of_birth = year+'-'+month+'-'+day user.birthday = date_of_birth user.email = form.cleaned_data['email'] user.role = 'client' user.first_name = form.cleaned_data['first_name'] user.phone_number = '' user.zip_code = form.cleaned_data['zip_code'] user.last_name = form.cleaned_data['last_name'] user.set_password(form.cleaned_data['password']) user.save() confirm_register_mail(request, user.email, user.first_name, user.last_name, user.zip_code) new_user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password'], ) login(request, new_user) messages.success(request, "You have registered successfully.") else: response.set_cookie('registr_error', 'error') cache.set('registartion_error', RegistrationForm(request.POST)) return response
def create(self, *args, **kwargs): serializer = self.serializer_class(data=self.request.data) serializer.is_valid(raise_exception=True) username = serializer.data.get('username') phone = serializer.data.get('phone') email = serializer.data.get('email') user = User() user.set_password(serializer.data.get('password')) user.email = email user.username = username user.phone = phone countryId = serializer.data.get('countryName') country_name = Country.objects.get(id=countryId) stateId = serializer.data.get('stateName') state_name = State.objects.get(id=stateId) cityId = serializer.data.get('cityName') city_name = City.objects.get(id=cityId) user.countryName = country_name user.stateName = state_name user.cityName = city_name ut.confirmation_email(email, user) user.save() token, created = Token.objects.get_or_create(user=user) return Response(data={'status': status.HTTP_200_OK,'token':token.key}, status=status.HTTP_200_OK)
def generate_users(request, times): # NOTE: passwords will not be hash correctly for i in range(0, times): u = User() u.email = f"{random_text('uniq', 20)}@g.com" u.password = random_text('t', 10).replace(' ', '') u.save() return HttpResponse(f'{times} Users created !')
def create(self, validated_data): user = User() user.set_password(validated_data["password"]) user.email = validated_data['email'] user.first_name = validated_data['first_name'] user.last_name = validated_data['last_name'] user.phone_number = validated_data['phone_number'] return user
def setUpTestData(cls): user = User() user.username = '******' user.password = '******' user.email = '*****@*****.**' user.first_name = '유' user.last_name = '저명' user.save()
def create_user(): user = User() user.username = request.form.get('username', None) user.first_name = request.form.get('first_name', '') user.last_name = request.form.get('last_name', '') user.email = request.form.get('email', '') user.account = request.form.get('account', None) user.set_password(request.form.get('password', '')) user.save() return redirect(url_for('accounts.users'))
def add_workers(request): for i in range(8): user = User() user.username = f'new_foreman{i+1}' user.email = f'new_foreman@new_foreman.com{i+1}' user.first_name = "Foreman" user.last_name = str(i + 1) user.is_foreman = True user.set_password('123') user.save() return HttpResponse("done")
def create_owner(self): user = User() user.username = self.email user.email = self.email user.set_password(get_random_string()) user.is_active = True user.save() # Add organization user to the NGO group user.groups.add(Group.objects.get(name=NGO_GROUP)) return user
def test_creating_new_user(self): user = User() user.username = "******" user.email = "*****@*****.**" user.set_password("test") user.full_clean() user.save() all_users = User.objects.all() self.assertEqual(len(all_users), 1) user_from_database = all_users[0] self.assertEquals(user_from_database, user)
def get(self, request, *args, **kwargs): sso_code = request.GET.get('code') url = '{0}/accessToken?client_id={1}&client_secret={2}&redirect_uri={3}&code={4}&grant_type=authorization_code'.format( self.oauth_api, self.client_id, self.client_secret, self.redirect_uri, sso_code) _, token = HttpRequests().get(url) try: access_token = json.loads(token)['access_token'] _, user = HttpRequests().get('%s/profile?access_token=%s' % (self.oauth_api, access_token)) user_info = json.loads(user) user_id = user_info['id'] user_job_number = user_info['empid'] user_email = user_info['email'] user_name = user_info['name'] user_display = user_info['username'] import random password = "".join( random.sample( 'abcdefghijklmnopqrstuvwxyzAbcDfGijKnMnopqrStuvvxYZ0123456789', 8)) if not User.objects.filter(username=user_job_number).exists(): user = User() user.username = user_job_number user.password = make_password(password) user.password2 = cryptor.encrypt(password) user.display = user_display user.email = user_email user.save() try: # 添加到默认组,默认组设置最小权限 group = Group.objects.get(id=1) user.groups.add(group) except Exception: print('无id=1的权限组,无法默认添加') user = User.objects.get(username=user_job_number) # 调用django内置登录方法,防止管理后台二次登录 login(request, user) next_url = request.GET.get("next") if request.GET.get( "next", None) else reverse("accounts:profile") return HttpResponseRedirect(next_url) except: print(traceback.print_exc()) return render(request, 'login.html')
def register_contractor_user(request): if request.method == 'POST': user = User() user.username = request.POST.get('username') user.email = request.POST.get('email') user.first_name = request.POST.get('first_name') user.last_name = request.POST.get('last_name') user.set_password(request.POST.get('password1')) user.user_type = 1 co = ContractorInformation() co.save() user.contractor_information = co user.save() return HttpResponseRedirect('/') return render(request, 'accounts/register-contractor.html', {})
def register_property_owner_user(request): if request.method == 'POST': user = User() user.username = request.POST.get('username') user.email = request.POST.get('email') user.first_name = request.POST.get('first_name') user.last_name = request.POST.get('last_name') user.set_password(request.POST.get('password1')) user.user_type = 0 po = PropertyOwnerInformation() po.save() user.property_owner_information = po user.save() return HttpResponseRedirect('/') return render(request, 'accounts/register-owner.html', {})
def add_foreman(request): if (not request.user.is_engineer): return HttpResponse("403 forbidden") if (request.method == 'POST'): worker = User() if (User.objects.filter(email=request.POST['email'])): messages.add_message(request, messages.INFO, 'Email already Exists') return redirect(reverse("tower:engineer_foremen")) worker.email = request.POST['email'] worker.username = request.POST['email'] worker.is_foreman = True worker.set_password(request.POST['password']) worker.first_name = request.POST['first_name'] worker.last_name = request.POST['last_name'] worker.save() messages.add_message(request, messages.SUCCESS, 'created successfuly') return redirect(reverse("tower:engineer_foremen")) return HttpResponse('forbidden')
def save(self, commit=True): ministry = super(MinistryRegisterForm, self).save() ld = self.data['leader'] ldv = self.data['leader_value'] ld = ld.split(', ') ldv = ldv.split(', ') ld = [{'key': l, 'value': v} for l, v in zip(ld, ldv)] for i in ld: if i is not None and i['value'] != "": us = User() if i['key'] == "" else get_object_or_404( User, pk=int(i["key"])) if us.pk is None: us.name = i['value'] lu = User.objects.all().order_by('-date_joined').first() us.username = settings.DEFAULT_USERNAME + str(lu.pk + 1) us.email = settings.DEFAULT_USERNAME + str(lu.pk + 1) + "@scale.br" us.set_password(settings.DEFAULT_PASSWORD) us.save() ministry.leader.add(us) if commit: ministry.save() return ministry
from accounts.models import User usernames = ["rolexlub", "overflap", "bloodedwheel", "analysingcinder", "adjointsoap", "stamplark", "leepseaborgium", "cogsignoramus", "cheekszigzag", "pharmacistaustrina", "planumhandy", "obiwanunbalanced", "limitedimpatient", "junkielumber", "unsungtarragon", "pavingurge", "steelclouds", "spatialassert", "signpostflintshire", "planturd", "circularsac", "stimulusaustralian", "viralextinction", "retrievedthing", "harlotwhile", "accusedcrusted", "luckstructure", "octavestnt", "purringmince", "bureaucratblanket", "surereceived", "dusterargument", "broomidentity", "cribknock", "hostilemoisture", "boldoblongata", "needlessinteger", "actionlocation", "daffygelatin", "russianrockers", "burkittjoined", "profitabledelphinus", "eczemawazzack", "madagascanfermented", "inquiryterrine", "tissueclotted", "rowinnate", "stunningmembrane", "analystheliosphere", "linesshortened", "whirrfrayed", "incompletegallivant", "cameramanarboreal", "partnerenvious", "basementlichen", "drunkenplutonium", "orangecreatures", "beautyracket", "dunbirdbump", "performerupstage", "bracevariant", "gammaspatial", "shearstraws", "remorsefulfortran", "giftshoppanoramic", "pandersmodulo", "womanteeming", "idolizedshale", "boneheadjolt", "cruelsection", "timergorged", "guaranteecyclist", "tskmycelium", "blankbuttery", "celerylifting", "peregrinehashtag", "hoprumble", "phewhollow", "analyticpopped", "luckyapproval", "bobolinkelearning", "towelswedge", "magicalhooded", "demonicwilted", "wistfulsenator", "battervulgar", "gainfuljohn", "bookrobin", "lavishledge", "nonchalantdirectly", "stoicpopper", "sporesamong", "pigrootblade", "pinwheeladvice", "paedophileout", "laddermusty", "caringglazier", "amedeirustic", "anotherexchange", "surdunease", "bishopaxis", "toolkitcardigan", "oreclapper", "weighgatz", "tartvolt", "reactivityrule", "balanceddish", "fishjordanian", "changelogs", "groggydml", "devicepurge", "tastelessgracious", "sherpatanager", "bloviateteenytiny", "incisionunits", "oppositecheerful", "indeedprostate", "waistmining", "conferenceabsurd", "hurrieddecline", "amiableverde", "meatsconverting", "punishmentbiodiesel", "jovialcompounds", "dillcool", "resourcescrowned", "verdeused", "soupyadze", "registerid", "twosphene", "penumbralottery", "cerebellummutant", "discerningstrontium", "wheytilted", "adhesiontektite", "effectstone", "drinkpitcher", "foolishant", "troublingverb", "insomniaarsenic", "pressurewalking", "stuffobesity", "savelogout", "homelessbohr", "uspride", "hideoussoftball", "blondaorta", "possetnodding", "subduralfill", "superbthread", "whirlwindmule", "initialchivalrous", "disksfels", "snappingtricky", "unctionhomesick", "fealonging", "leadingemacs", "processerdole", "continueavoid", "meanblushing", "providedbiscuit", "notelated", "boarmonths", "inedibledivergent", "bowlingsnouted", "damnedmisguided", "helpingartiste", "recommendtorque", "possessivemono", "raftertour", "shovelerprocess", "throwingripe", "bushmacedonian", "shiningsnorkel", "payingliquid", "handleday", "seafowloverlooked", "creamsglasses", "enginefunctions", "wholetheir", "bungeewitted", "godwitinvoices", "modelfrustum", "peachesgermanium", "bailgateway", "hootrelated", "informmidwife", "leastespuma", "savesthin", "estimatormerchants", "centaurspoppy", "bodyplan", "dunkingannouncer", "floppyskinned", "junebalmer", "fanfareeasy", "resistorconic", "matbitwise", "bazookadairy", "jeerderivation"] for username in usernames: user = User() user.set_password('test') user.username = username user.email = "*****@*****.**" % username user.phone_verified = True user.save()
def register(request): if request.method == "POST": print(request.POST) print(request.FILES) user = User() user.username = request.POST.get('username') user.first_name = request.POST.get('firstname') user.last_name = request.POST.get('lastname') user.set_password(request.POST.get('password')) user.email = request.POST.get('email_address') user.phone_number = request.POST.get('phone_number') user.profile_bio = request.POST.get('profile_bio') # print(request.FILES) image = request.FILES.get('profile_image') if image: user.image = image user.save() # skill skills = 0 for i in request.POST: if i.startswith('skill_profile_'): skills += 1 for i in range(skills): # print(request.POST.get('skill_profile_{}'.format(i))) # print(request.POST.get('skill-level_{}'.format(i))) skill = Skill() skill.name = request.POST.get('skill_profile_{}'.format(i)) skill.level = request.POST.get('skill-level_{}'.format(i)) skill.user = user skill.save() # interest interests = 0 for i in request.POST: if i.startswith('interest_profile_'): interests += 1 for i in range(interests): interest = Interest() interest.name = request.POST.get('interest_profile_{}'.format(i)) interest.user = user interest.save() # equipment equipment_set = 0 for i in request.POST: if i.startswith('equipment_profile_'): equipment_set += 1 for i in range(equipment_set): equipment = Equipment() equipment.name = request.POST.get('equipment_profile_{}'.format(i)) equipment.condition = request.POST.get('equipment_condition_{}'.format(i)) equipment.user = user equipment_image = request.FILES.get('equipment_image_{}'.format(i)) # print(request.FILES) if equipment_image: equipment.image = equipment_image equipment.save() return render(request, "accounts/profile_reg_form.html")
def register_page(request): if request.user.is_authenticated() and (request.user.admin or request.user.manager or request.user.employee): form = RegisterForm(request.POST or None) address = AddressForm(request.POST or None) kid = KidForm(request.POST or None) instance = None if request.user.admin: instance = User.objects.all() elif request.user.manager: instance = User.objects.all().filter(admin=False) daycare = DaycareForm(request.user) context = { "form": form, "address": address, "daycare": daycare, "kid": kid, "instance": instance, } if request.POST: if request.POST['choices'] == 'admin': if form.is_valid() and address.is_valid(): name_age_pairs = zip( request.POST.getlist('child_first_name'), request.POST.getlist('child_last_name'), request.POST.getlist('gender')) profile = User() profile.email = form.cleaned_data['email'] profile.set_password(form.cleaned_data["password1"]) #profile.password = form.cleaned_data['password2'] profile.adult_first_name = form.cleaned_data[ 'adult_first_name'] profile.adult_last_name = form.cleaned_data[ 'adult_last_name'] profile.active = True profile.admin = True profile.staff = True profile.manager = False profile.employee = False profile.parent = False address_profile = Address() address_profile.address_line_1 = address.cleaned_data[ 'address_line_1'] address_profile.address_line_2 = address.cleaned_data[ 'address_line_2'] address_profile.city = address.cleaned_data['city'] address_profile.country = address.cleaned_data['country'] address_profile.province = address.cleaned_data[ 'postal_code'] address_profile.postal_code = address.cleaned_data[ 'province'] address_profile.home_phone = address.cleaned_data[ 'home_phone'] address_profile.cell_phone = address.cleaned_data[ 'cell_phone'] address_profile.save() profile.user_address = address_profile profile.save() all_selected_daycares = request.POST.getlist('daycare') if all_selected_daycares is not None: for data in all_selected_daycares: temporary_daycare = Daycare.objects.get(name=data) profile.daycare.add(temporary_daycare.id) profile.save() if kid.is_valid() and name_age_pairs is not None: data_dicts = [{ 'child_first_name': child_first_name, 'child_last_name': child_last_name, 'gender': gender } for child_first_name, child_last_name, gender in name_age_pairs] for data in data_dicts: if data['child_first_name'] != "" and data[ 'child_last_name'] != "": profile_kid = Kid() profile_kid.parent = profile profile_kid.child_first_name = data[ 'child_first_name'] profile_kid.child_last_name = data[ 'child_last_name'] profile_kid.gender = data['gender'] profile_kid.save() return redirect("/register/") elif request.POST['choices'] == 'manager': if form.is_valid() and address.is_valid(): name_age_pairs = zip( request.POST.getlist('child_first_name'), request.POST.getlist('child_last_name'), request.POST.getlist('gender')) profile = User() profile.email = form.cleaned_data['email'] profile.set_password(form.cleaned_data["password1"]) #profile.password = form.cleaned_data['password2'] profile.adult_first_name = form.cleaned_data[ 'adult_first_name'] profile.adult_last_name = form.cleaned_data[ 'adult_last_name'] profile.active = True profile.admin = False profile.staff = False profile.employee = False profile.manager = True profile.parent = False address_profile = Address() address_profile.address_line_1 = address.cleaned_data[ 'address_line_1'] address_profile.address_line_2 = address.cleaned_data[ 'address_line_2'] address_profile.city = address.cleaned_data['city'] address_profile.country = address.cleaned_data['country'] address_profile.province = address.cleaned_data[ 'postal_code'] address_profile.postal_code = address.cleaned_data[ 'province'] address_profile.home_phone = address.cleaned_data[ 'home_phone'] address_profile.cell_phone = address.cleaned_data[ 'cell_phone'] address_profile.save() profile.user_address = address_profile profile.save() all_selected_daycares = request.POST.getlist('daycare') if all_selected_daycares is not None: for data in all_selected_daycares: temporary_daycare = Daycare.objects.get(name=data) profile.daycare = Daycare.objects.get( id=temporary_daycare.id) profile.save() if kid.is_valid() and name_age_pairs is not None: data_dicts = [{ 'child_first_name': child_first_name, 'child_last_name': child_last_name, 'gender': gender } for child_first_name, child_last_name, gender in name_age_pairs] for data in data_dicts: if data['child_first_name'] != "" and data[ 'child_last_name'] != "": profile_kid = Kid() profile_kid.parent = profile profile_kid.child_first_name = data[ 'child_first_name'] profile_kid.child_last_name = data[ 'child_last_name'] profile_kid.gender = data['gender'] profile_kid.save() return redirect("/register/") elif request.POST['choices'] == 'employee': if form.is_valid() and address.is_valid(): name_age_pairs = zip( request.POST.getlist('child_first_name'), request.POST.getlist('child_last_name'), request.POST.getlist('gender')) profile = User() profile.email = form.cleaned_data['email'] profile.set_password(form.cleaned_data["password1"]) #profile.password = form.cleaned_data['password2'] profile.adult_first_name = form.cleaned_data[ 'adult_first_name'] profile.adult_last_name = form.cleaned_data[ 'adult_last_name'] profile.active = True profile.admin = False profile.staff = False profile.manager = False profile.employee = True profile.parent = False address_profile = Address() address_profile.address_line_1 = address.cleaned_data[ 'address_line_1'] address_profile.address_line_2 = address.cleaned_data[ 'address_line_2'] address_profile.city = address.cleaned_data['city'] address_profile.country = address.cleaned_data['country'] address_profile.province = address.cleaned_data[ 'postal_code'] address_profile.postal_code = address.cleaned_data[ 'province'] address_profile.home_phone = address.cleaned_data[ 'home_phone'] address_profile.cell_phone = address.cleaned_data[ 'cell_phone'] address_profile.save() profile.user_address = address_profile profile.save() all_selected_daycares = request.POST.getlist('daycare') if all_selected_daycares is not None: for data in all_selected_daycares: temporary_daycare = Daycare.objects.get(name=data) profile.daycare = Daycare.objects.get( id=temporary_daycare.id) profile.save() if kid.is_valid() and name_age_pairs is not None: data_dicts = [{ 'child_first_name': child_first_name, 'child_last_name': child_last_name, 'gender': gender } for child_first_name, child_last_name, gender in name_age_pairs] for data in data_dicts: if data['child_first_name'] != "" and data[ 'child_last_name'] != "": profile_kid = Kid() profile_kid.parent = profile profile_kid.child_first_name = data[ 'child_first_name'] profile_kid.child_last_name = data[ 'child_last_name'] profile_kid.gender = data['gender'] profile_kid.save() return redirect("/register/") elif request.POST['choices'] == 'parent': if form.is_valid() and address.is_valid(): name_age_pairs = zip( request.POST.getlist('child_first_name'), request.POST.getlist('child_last_name'), request.POST.getlist('gender')) profile = User() profile.email = form.cleaned_data['email'] profile.set_password(form.cleaned_data["password1"]) #profile.password = form.cleaned_data['password2'] profile.adult_first_name = form.cleaned_data[ 'adult_first_name'] profile.adult_last_name = form.cleaned_data[ 'adult_last_name'] profile.active = True profile.admin = False profile.staff = False profile.manager = False profile.employee = False profile.parent = True address_profile = Address() address_profile.address_line_1 = address.cleaned_data[ 'address_line_1'] address_profile.address_line_2 = address.cleaned_data[ 'address_line_2'] address_profile.city = address.cleaned_data['city'] address_profile.country = address.cleaned_data['country'] address_profile.province = address.cleaned_data[ 'postal_code'] address_profile.postal_code = address.cleaned_data[ 'province'] address_profile.home_phone = address.cleaned_data[ 'home_phone'] address_profile.cell_phone = address.cleaned_data[ 'cell_phone'] address_profile.save() profile.user_address = address_profile profile.save() all_selected_daycares = request.POST.getlist('daycare') if all_selected_daycares is not None: for data in all_selected_daycares: temporary_daycare = Daycare.objects.get(name=data) profile.daycare = Daycare.objects.get( id=temporary_daycare.id) profile.save() if kid.is_valid() and name_age_pairs is not None: data_dicts = [{ 'child_first_name': child_first_name, 'child_last_name': child_last_name, 'gender': gender } for child_first_name, child_last_name, gender in name_age_pairs] for data in data_dicts: if data['child_first_name'] != "" and data[ 'child_last_name'] != "": profile_kid = Kid() profile_kid.parent = profile profile_kid.child_first_name = data[ 'child_first_name'] profile_kid.child_last_name = data[ 'child_last_name'] profile_kid.gender = data['gender'] profile_kid.save() return redirect("/register/") else: pass else: return redirect("/") return render(request, "accounts/register.html", context)
def save(self): self.clean() cleaned_data = self.cleaned_data userManager = MyUserManager() email = cleaned_data.get('email') firstName = cleaned_data.get('firstName') lastName = cleaned_data.get('lastName') user_type = None if self.is_employer_selected(): user_type = USER_TYPE_EMPLOYER else: user_type = USER_TYPE_CANDIDATE password = cleaned_data.get('password') print(user_type) user = User() user.email = email user.firstName = firstName user.lastName = lastName user.user_type = user_type user.set_password(password) user.save() if cleaned_data.get('preferredName') != '' and cleaned_data.get( 'preferredName') != None: preferredName = PreferredName() preferredName.user = user preferredName.preferredName = cleaned_data.get('preferredName') preferredName.save() if self.is_employer_selected(): employer = Employer() employer.user = user if self.is_createCompany_selected(): company = Company() company.name = cleaned_data.get('companyName') company.address = cleaned_data.get('address') company.website = cleaned_data.get('website') company.profile = cleaned_data.get('profile') company.image = cleaned_data.get('image') company.save() employer.company = company else: employer.company = get_object_or_404( Company, pk=cleaned_data.get('company')) employer.save() else: candidate = Candidate() candidate.user = user candidate.studentID = cleaned_data.get('studentID') candidate.creditCompleted = cleaned_data.get('creditCompleted') candidate.program = cleaned_data.get('program') candidate.creditLeft = cleaned_data.get('creditLeft') candidate.gpa = cleaned_data.get('gpa') candidate.internationalStudent = cleaned_data.get( 'internationalStudent') candidate.travel = cleaned_data.get('travel') candidate.timeCommitment = cleaned_data.get('timeCommitment') candidate.transcript = cleaned_data.get('transcript') candidate.save() for lan in self.languageFieldsNames: language = Language() language.language = cleaned_data.get(lan['language']) language.fluency = cleaned_data.get(lan['proficiency']) language.details = cleaned_data.get(lan['details']) language.user = user language.save() return user