def create(self, user_validate_data, profile_validate_data): user = self.model(**user_validate_data) profile = Profile(**profile_validate_data) profile.save() user.profile = profile user.save() return user
def student_status_confirm(request): import urllib import simplejson as json from hashlib import md5 import settings user = request.user if not user.is_authenticated(): raise Http302('/login/') try: userprofile = user.get_profile() except: userprofile = Profile(user=user) login = request.POST.get('login', '') password = md5(request.POST.get('password', '').encode('utf-8')).hexdigest() params = "login=%s&password=%s" % (login.encode('utf-8'), password) result = urllib.urlopen( settings.EDUCON_URL, params).read() or u"Произошла досадная ошибка, попробуйте позже." try: userprofile.student_id = int(result) userprofile.save() return HttpResponse(u"Статус студента подтверждён, обновите профиль.", mimetype="text/plain") except: return HttpResponse(content=result, mimetype="text/plain", status=500)
def register(request): if request.method == "POST": try: user = User.objects.create_user( email=request.POST['email'], password=request.POST['password'], ) user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.save() profile = Profile() profile.user = user profile.save() is_employer = (request.POST['is_employer'] == '0') if (is_employer): company = Company() company.user = user company.save() return render(request, 'registration/edit.html', {'is_company': is_employer}) except: return render(request, 'registration/edit.html', {'is_company': False}) else: return render(request, 'registration/registration.html')
def check_users(self): start_time = time.time() emails = [] cursor = connection.cursor() cursor.execute("SELECT * FROM smf_members;") rows = cursor.fetchall() for row in rows: try: user = User.objects.get(username=row[1]) except User.DoesNotExist: try: print "User %s does not exist. Creating" % row[1] user = User.objects.create_user(row[1], row[12]) user.set_unusable_password() user.save() profile = Profile() profile.user = user profile.personal_text = row[13] profile.location = row[18] profile.old_user_id = row[0] profile.website = row[17] profile.title = row[32] profile.save() except Exception, e: print "Could not create user %s, %s" % (row[1], str(e))
def create_profile(user, **kwargs): profile = Profile( user=user, first_name="John", last_name="Doe", waiver=True, agreement=True, photo_release=False, **kwargs) profile.save() return profile
def accounts(request): #person = User.objects.create_user('Vista@Salvation', '*****@*****.**', 'password') #person.save() person = User.objects.get(username='******') vol = Group.objects.get(name="Salvation Farms Administrator") person.groups.add(vol) memorg = MemOrg.objects.get(name="MemberOrg0") userprof = Profile(user=person, first_name = 'Marcella', last_name="Houghton", member_organization=memorg) userprof.save() counties = County.objects.all() for county in counties: userprof.counties.add(county) return HttpResponse('that all worked')
def email_confirm(request, user_id, code): user = User.objects.get(id=user_id) true_code = uuid5(UUID(settings.UUID_NAMESPACE_FOR_EMAIL_CONFIRM), str(user.email)) if str(true_code) == str(code): try: profile = user.get_profile() except: profile = Profile(user=user) profile.is_email_confirmed = True profile.save() return HttpResponse(u'Ваш email подтвержден') else: return HttpResponse(u'Код подтверждения не верен')
def test_model(self): testProf1 = Profile(name="Test", username="******", password="******", \ lat=123, lng=123, school="school", \ courses="courses", preferences="preferences", \ interests="interests") testProf1.save() testProf2 = Profile(name="Test", username="******", password="******", \ lat=123, lng=123, school="school", \ courses="courses", preferences="preferences", \ interests="interests") testProf2.save() match = Match(user1=testProf1, user2=testProf2, score=100, user1HasMatched=False, user2HasMatched=False, user1accepted=True, user2accepted=True) match.save() msg = Message(sender=testProf1, matchID=match, message="message") msg.save() assert msg.__str__() == "message" assert msg.toJson()["sender"] == testProf1.id assert createMessage(testProf1.id, match.id, "Hello", False)["id"] != -1 assert createMessage(testProf1.id, match.id, "Hello", True)["id"] != -1 assert createMessage(1000, match.id, "Hello", False)["id"] == -1 assert messageLog(match.id) != None
def edit(request): from forms import ProfileForm context = {} user = request.user if not user.is_authenticated(): raise Http302('/login/') try: profile = user.get_profile() except: profile = None if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): data = form.cleaned_data user.last_name = data['last_name'] user.first_name = data['first_name'] drop_email = user.email != data['email'] user.email = data['email'] user.save() if data['middle_name'] or data['subscription']: if profile: profile.middle_name = data['middle_name'] profile.subscription = data['subscription'] else: profile = Profile(user=user, middle_name=data['middle_name'], subscription=data['subscription']) if drop_email: profile.is_email_confirmed = False profile.save() return u'Данные успешно сохранены' context['form'] = form else: data = { 'last_name': user.last_name, 'first_name': user.first_name, 'email': user.email } if profile: data['middle_name'] = profile.middle_name data['subscription'] = profile.subscription context['form'] = ProfileForm(initial=data) context['profile'] = profile return template_loader.get_template("profile/edit.html").render( RequestContext(request, context))
def edit(request): from forms import ProfileForm context = {} user = request.user if not user.is_authenticated(): raise Http302('/login/') try: profile = user.get_profile() except: profile = None if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): data = form.cleaned_data user.last_name = data['last_name'] user.first_name = data['first_name'] drop_email = user.email != data['email'] user.email = data['email'] user.save() if data['middle_name'] or data['subscription']: if profile: profile.middle_name = data['middle_name'] profile.subscription = data['subscription'] else: profile = Profile(user=user, middle_name=data['middle_name'], subscription = data['subscription']) if drop_email: profile.is_email_confirmed = False profile.save() return u'Данные успешно сохранены' context['form'] = form else: data = {'last_name':user.last_name, 'first_name': user.first_name, 'email':user.email} if profile: data['middle_name'] = profile.middle_name data['subscription'] = profile.subscription context['form'] = ProfileForm(initial=data) context['profile'] = profile return template_loader.get_template("profile/edit.html").render( RequestContext(request, context))
def convert_users(self): start_time = time.time() emails = [] users = User.objects.values('email') for user in users: emails.append(user["email"]) print emails cursor = connection.cursor() cursor.execute("SELECT * FROM smf_members;") rows = cursor.fetchall() for row in rows: old_id = row[0] username = row[1] date_registered = row[2] post_count = row[3] last_login = row[6] email = row[12] personal_text = row[13] gender = row[14] website = row[17] location = row[18] if email in emails: user = User.objects.get(email=row[12]) profile, created = Profile.objects.get_or_create(user=user) if created: profile.save() else: try: user = User.objects.create_user(row[1], row[12]) user.set_unusable_password() user.save() profile = Profile() profile.user = user profile.personal_text = row[13] profile.location = row[18] profile.old_user_id = row[0] profile.website = row[17] profile.title = row[32] profile.save() except Exception, e: with open("conversion_errors.log", "a") as myfile: myfile.write("%s \r\n %s\r\n\r\n" % (row[1], str(e)))
def _log_user_activity(userprofile, activity, link, function="", ip=""): activity = Activity.objects.create(user=userprofile.user, activity=activity, link=link) if (ip): activity.ip_addr = ip activity.save() if (activity.activity == "click"): userprofile.clicks += 1 if (function): userprofile.function = function userprofile.save() return activity
def _log_user_activity(userprofile, activity, link, function="", ip=""): activity = Activity.objects.create(user=userprofile.user,activity=activity,link=link) if(ip): activity.ip_addr = ip activity.save() if(activity.activity=="click"): userprofile.clicks += 1 if(function): userprofile.function = function userprofile.save() #print '*'*100 #print 'activity', activity, activity.activity return activity
def new_view(request): try: token = request.POST['token'] except KeyError: return generate_json(success=False, data={'code': TOKEN_NOT_FOUND}) try: profile = Profile.authenticate(token) except AuthenticationFailedError: return generate_json(success=False, data={'code': INVALID_TOKEN}) request.profile = profile return view(request)
def save_profile(backend, user, response, *args, **kwargs): try: profile = user.profile except: profile = Profile(user_id=user.id) image_url = None print(response) if backend.name == 'twitter': image_url = response.get('profile_image_url_https', '').replace('_normal', '') elif backend.name == 'facebook': fb_id = response.get('id') if fb_id: image_url = 'https://graph.facebook.com/{}/picture?height=300&width=300'.format( fb_id) elif backend.name == 'google-oauth2': try: image_url = response['image']['url'].replace('sz=50', 'sz=300') except: pass if image_url: profile.social_photo_url = image_url profile.save()
def student_status_confirm(request): import urllib import simplejson as json from hashlib import md5 import settings user = request.user if not user.is_authenticated(): raise Http302('/login/') try: userprofile = user.get_profile() except: userprofile = Profile(user=user) login = request.POST.get('login', '') password = md5(request.POST.get('password', '').encode('utf-8')).hexdigest() params = "login=%s&password=%s"%(login.encode('utf-8'), password) result = urllib.urlopen(settings.EDUCON_URL, params).read() or u"Произошла досадная ошибка, попробуйте позже." try: userprofile.student_id = int(result) userprofile.save() return HttpResponse(u"Статус студента подтверждён, обновите профиль.", mimetype="text/plain") except: return HttpResponse(content=result, mimetype="text/plain", status=500)
def test_to_string(self): testProf1 = Profile(name="Test", username="******", password="******", \ lat=123, lng=123, school="school", \ courses="courses", preferences="preferences", \ interests="interests") testProf1.save() testProf2 = Profile(name="Test", username="******", password="******", \ lat=123, lng=123, school="school", \ courses="courses", preferences="preferences", \ interests="interests") testProf2.save() match = Match(user1=testProf1, user2=testProf2, score=100, user1HasMatched=False, user2HasMatched=False, user1accepted=True, user2accepted=True) match.save() msg = Message(sender=testProf1, matchID=match, message="message") msg.save() assert msg.__str__() == "message"
def set_initial_user_names(request, user, sociallogin=None, **kwargs): """ sociallogin.account.provider # e.g. 'twitter' sociallogin.account.get_avatar_url() sociallogin.account.get_profile_url() sociallogin.account.extra_data['screen_name'] """ profile = Profile() if sociallogin: if sociallogin.account.provider == 'facebook': profile.gender_type = sociallogin.account.extra_data['gender'] #verified = sociallogin.account.extra_data['verified'] #I want to get country and city of user from ip address. from ipware import get_client_ip client_ip, is_routable = get_client_ip(request) if client_ip is None: pass # Unable to get the client's IP address else: # We got the client's IP address if is_routable: # The client's IP address is publicly routable on the Internet import requests r = requests.get('http://usercountry.com/v1.0/json/' + str(client_ip)) result = r.json() if result['status'] == "success": profile.country = result['country']['alpha-2'] profile.city = result['region']['city'] else: #result returns failure pass else: pass # The client's IP address is private profile.user = user profile.save()
def register(request): args={} args.update(csrf(request)) if request.POST: username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] accountType = request.POST['accountType'] user = User.objects.create_user(username=username,email=email,password=password) profile = Profile(user=user) if request.POST.get('ref') is not None: ref = request.POST['ref'] userReferer = User.objects.get(username=ref) userRefererProfile = userReferer.profile userRefererProfile.members_referred+=1 userRefererProfile.save() else: pass if accountType == 'influencer': profile.influencer = True elif accountType == 'brand': profile.brand = True profile.save() user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return HttpResponseRedirect('/perkboard/') else: return HttpResponse('Wrong account details') return HttpResponseRedirect('/perkboard/') else: return HttpResponse('Something went wrong!')
def newUser(request): notice = '' if request.method == 'POST': form = ExtendedRegistrationForm(request.POST) if form.is_valid(): new_user = User.objects.create_user( form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password1'] ) profile = Profile( first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], address_one=form.cleaned_data['address_one'], address_two=form.cleaned_data['address_two'], city=form.cleaned_data['city'], state=form.cleaned_data['state'], zipcode=form.cleaned_data['zipcode'], notes=form.cleaned_data['notes'], tasks_gleaning=form.cleaned_data['tasks_gleaning'], tasks_farm_pickups=form.cleaned_data['tasks_farm_pickups'], tasks_delivery=form.cleaned_data['tasks_delivery'], tasks_admin=form.cleaned_data['tasks_admin'], tasks_processing=form.cleaned_data['tasks_processing'], age=form.cleaned_data['age'], phone=form.cleaned_data['phone'], phone_type=form.cleaned_data['phone_type'], preferred_method=form.cleaned_data['preferred_method'], ecfirst_name=form.cleaned_data['ecfirst_name'], eclast_name=form.cleaned_data['eclast_name'], ecrelationship=form.cleaned_data['ecrelationship'], ecphone=form.cleaned_data['ecphone'], user=new_user, waiver=form.cleaned_data['waiver'], agreement=form.cleaned_data['agreement'], photo_release=form.cleaned_data['photo_release'], opt_in=form.cleaned_data['opt_in'], ) profile.save() for county in form.cleaned_data['vt_counties']: profile.counties.add(county) for county in form.cleaned_data['ny_counties']: profile.counties.add(county) notice = ('New Volunteer ' + profile.first_name + ' ' + profile.last_name + ' has been created.') form = ExtendedRegistrationForm() else: form = ExtendedRegistrationForm() users = [] if request.user.has_perm('userprofile.uniauth'): users = User.objects.all().order_by('-date_joined')[:20] else: for county in request.user.profile.member_organization.counties.all(): for user in User.objects.all(): if county in user.profile.counties.all(): users.append(user) return render( request, 'userprofile/newuser.html', {'form': form, 'users': users, 'notice': notice})
def index(request): #return HttpResponse('worked') if not Group.objects.all(): vol = Group(name="Volunteer") vol.save() ed = Group(name="Member Organization Executive Director") ed.save() mc = Group(name="Member Organization Glean Coordinator") mc.save() sal = Group(name="Salvation Farms Administrator") sal.save() salc = Group(name="Salvation Farms Coordinator") salc.save() ed = Group.objects.get(name="Member Organization Executive Director") if not ed.permissions.all(): mo_list = [Announcement, Template, Distro, GleanEvent, Farm, RecipientSite, Profile, MemOrg, Post] uni_list = [Announcement, Template, Distro, GleanEvent, Farm, FarmLocation, Contact, RecipientSite, Profile, MemOrg, County, Post] mc = Group.objects.get(name="Member Organization Glean Coordinator") sal = Group.objects.get(name="Salvation Farms Administrator") salc = Group.objects.get(name="Salvation Farms Coordinator") for model in mo_list: content_type = ContentType.objects.get_for_model(model) perm = Permission.objects.get(codename='auth', content_type=content_type) ed.permissions.add(perm) mc.permissions.add(perm) sal.permissions.add(perm) salc.permissions.add(perm) for model in uni_list: content_type = ContentType.objects.get_for_model(model) perm = Permission.objects.get(codename='uniauth', content_type=content_type) sal.permissions.add(perm) salc.permissions.add(perm) if County.objects.filter(name='County1').exists(): return HttpResponse("<a href='/'>Go home.</a>") for i in range(memberorg_quant): new = MemOrg(name="MemberOrg"+str(i), description="This is the "+str(i)+"th member org in our gleaning collective!", counties = "A bunch of counties are covered by us, including {insert counties here}") new.save() newTemp = Template(template_name="Default template", body="<html><body>{{content}}{{glean.title}}{{glean.description}}{{rsvp}}{{info}}{{unsubscribe}}</body></html>", member_organization=new) newTemp.save() for i in range(recipient_sites): choices2 = range(memberorg_quant) choice2 = choices2.pop(random.choice(choices2)) memorg = MemOrg.objects.get(name="MemberOrg"+str(choice2)) new = RecipientSite(name="RecipientSite" + str(i), address_one = "515 Main Street", city="Morrisville", state="VT", zipcode="01771",member_organization=memorg) new.save() for i in range(county_quant): new = County(name="County"+str(i),description="County"+str(i), towns="Town"+str(i)) new.save() for i in range(user_quant): name = 'name' + str(i) choices2 = range(memberorg_quant) choice2 = choices2.pop(random.choice(choices2)) memorg = MemOrg.objects.get(name="MemberOrg"+str(choice2)) person = User.objects.create_user(name, '*****@*****.**', 'password') if name == "name0": vol = Group.objects.get(name="Salvation Farms Administrator") person.groups.add(vol) vol = None elif name == "name1": vol = Group.objects.get(name="Member Organization Executive Director") person.groups.add(vol) vol = None else: vol = Group.objects.get(name="Volunteer") person.groups.add(vol) vol = None userprof = Profile(user=person, first_name = 'firsty'+str(i),last_name='lasty'+str(i), member_organization=memorg) userprof.save() choices = range(county_quant) choice1 = choices.pop(random.choice(choices)) county = County.objects.get(name='County'+str(choice1)) userprof.counties.add(county) userprof.save() my_user = 0 my_county = 0 for i in range(farm_quant): if my_user >= user_quant: my_user = 0 if my_county >= county_quant: my_county = 0 choices2 = range(memberorg_quant) choice2 = choices2.pop(random.choice(choices2)) memorg = MemOrg.objects.get(name="MemberOrg"+str(choice2)) new = Farm(name="farm"+str(i),farm_type=FARM_TYPE[0][1],address_one="100 Main Street",address_two="apartment 3",city="Burlington",state="VT",description="generic farm",physical_is_mailing=True,phone_1='8025786266',email="*****@*****.**",direction="Many different directions",instructions="many instructions") new.save() new.member_organization.add(memorg) new.save() new.farmers.add(User.objects.all()[my_user]) new.counties.add(County.objects.all()[my_county]) my_user = my_user + 1 my_county = my_county + 1 my_farm = 0 my_county = 0 for i in range(loc_divinto_farms): if my_farm >= farm_quant: my_farm = 0 if my_county >= county_quant: my_county = 0 new = FarmLocation(farm=Farm.objects.all()[my_farm],name="location"+str(i),description="Grand Central Field",directions="all kinds of directions") new.save() new.counties.add(County.objects.all()[my_county]) my_farm = my_farm + 1 my_county = my_county + 1 return HttpResponse("Your data has been created. <a href='/'>Go home.</a>")
def newAdministrator(request, memorg_id): member_organization = get_object_or_404(MemOrg, pk=memorg_id) profile = request.user.profile if not request.user.has_perm('memberorgs.uniauth') and ( member_organization != profile.member_organization): return HttpResponseRedirect( reverse('memorgs:detailmemorg', args=(memorg_id,))) if request.method == 'POST': form = NewAdminForm(request.POST) existant_user = User.objects.filter( username=form.data["username"] ).exists() if not existant_user and form.is_valid(): new_user = User.objects.create_user( form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password']) new_profile = Profile(user=new_user, first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], phone=form.cleaned_data['phone'], member_organization=form.cleaned_data[ 'member_organization'] ) new_profile.save() for county in member_organization.counties.all(): new_profile.counties.add(county) if member_organization.name == 'Salvation Farms': if form.cleaned_data['access_level'] == 'PD': sal = Group.objects.get( name="Salvation Farms Administrator") new_user.groups.add(sal) else: salc = Group.objects.get( name="Salvation Farms Coordinator") new_user.groups.add(salc) else: if form.cleaned_data['access_level'] == 'PD': ed = Group.objects.get( name="Member Organization Executive Director") new_user.groups.add(ed) else: memc = Group.objects.get( name="Member Organization Glean Coordinator") new_user.groups.add(memc) if request.POST['action'] == 'Save': return HttpResponseRedirect( reverse('memorgs:detailmemorg', args=(memorg_id,))) else: form = NewAdminForm() if not request.user.has_perm('userprofile.uniauth'): form.fields['access_level'].choices = TRUNCATED_LEVELS form.fields['member_organization'].queryset = ( MemOrg.objects.filter(pk=memorg_id)) notice = 'Administrator account ' + new_user.username + '' ' has been created' return render(request, 'memberorgs/newadmin.html', {'form': form, 'notice': notice}) else: return HttpResponse( 'form.is_not_valid - probably the username is taken' ) form = NewAdminForm() form.fields['member_organization'].queryset = MemOrg.objects.filter( pk=memorg_id) if not request.user.has_perm('userprofile.uniauth'): form.fields['access_level'].choices = TRUNCATED_LEVELS return render(request, 'memberorgs/newadmin.html', {'form': form})
def user_save(sender, instance, created, signal, *args, **kwargs): if created: if instance.is_superuser or instance.is_staff: user_obj = User.objects.get(pk=instance.pk) profile_obj = Profile(user=user_obj, type='admin-person') profile_obj.save() else: user_obj = User.objects.get(pk=instance.pk) profile_obj = Profile(user=user_obj, type='employee-person') profile_obj.save() else: if instance.is_superuser or instance.is_staff: user_obj = User.objects.get(pk=instance.pk) profile_obj = Profile.objects.filter(user=user_obj).first() if profile_obj: employee_obj = Employee.objects.filter( profile=profile_obj).first() if employee_obj: instance.first_name = employee_obj.first_name instance.last_name = employee_obj.last_name # instance.first_name = employee_obj.e else: profile_obj.type = 'admin-person' profile_obj.save()
def home(request): if request.user.is_authenticated(): # return HttpResponseRedirect('/myprofile/') return redirect(userprofileviews.myprofile) login_form = LoginForm() signup_form = SignUpForm() message = "none" context = {"login": login_form, "signup": signup_form, "message": message} print request.POST if request.method == "POST": login_form = LoginForm(request.POST) signup_form = SignUpForm(request.POST) # print request.POST if ( "signup" in request.POST and signup_form.is_valid() ): # ------------------------------------------------------IF SIGN UP FORM-----------------------# username = signup_form.cleaned_data["username"] password = signup_form.cleaned_data["password"] print "--------------------------------SIGN UP FORM-------------------------------------------" print username print password # login_form = LoginForm() # signup_form = SignUpForm() # TRY TO SIGN UP try: User.objects.create_user(username, username, password) user = authenticate(username=username, password=password) login(request, user) if user is not None: print "PASS" print user newprofile = Profile(user=user) newprofile.save() return redirect(userprofileviews.first_time_user) except IntegrityError as e: # ------------------------------WRONG ERROR-----------------------------------# context = {"login": login_form, "signup": signup_form, "message": e.__cause__} return render_to_response("error.html", context) elif ( "login" in request.POST and login_form.is_valid() ): # --------------------------------------IF LOGIN FORM-------------------------------$ username = login_form.cleaned_data["username"] password = login_form.cleaned_data["password"] print "--------------------------------LOGIN FORM-------------------------------------------" print username print password login_form = LoginForm() signup_form = SignUpForm() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect("/myprofile/") else: print "user_not_active" else: login_form = LoginForm() signup_form = SignUpForm() return render(request, "index.html", context)
def create_profile(user, memorg): profile = Profile( user=user, first_name="John", last_name="Doe", member_organization=memorg, waiver=True, agreement=True ) profile.save() return profile