本文整理汇总了Python中core.models.UserProfile类的典型用法代码示例。如果您正苦于以下问题:Python UserProfile类的具体用法?Python UserProfile怎么用?Python UserProfile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了UserProfile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
def post(self, request, *args, **kwargs):
context = super(StaffFormView, self).get_context_data(**kwargs)
context['departments'] = CompanyDepartments.objects.all()
profile_form = UserProfileFrom(request.POST)
form = UserCreateForm(request.POST)
if form.is_valid() and profile_form.is_valid():
new_user = form.save()
new_user.email = request.POST.get('username')
new_user.save()
try:
department_id = CompanyDepartments.objects.get(uuid=request.POST.get('department'))
except CompanyDepartments.DoesNotExist:
department_id = None
user_profile = UserProfile(
user_id=new_user,
phone=request.POST.get('phone'),
home_phone=request.POST.get('home_phone'),
work_phone=request.POST.get('office_phone'),
department=department_id,
designation=request.POST.get('designation')
)
user_profile.save()
return HttpResponseRedirect("/staff-list/")
else:
context['form'] = form
context['profile_form'] = profile_form
return render(request, self.template_name, context)
示例2: user_create
def user_create(request):
from hashlib import sha1
ctx = {}
username = request.REQUEST.get("username")
password = request.REQUEST.get("password")
signature = request.REQUEST.get("signature")
email = request.REQUEST.get("email", "")
m = sha1()
m.update(":" + username + ":" + password + ":" + settings.SHARED_SECRET + ":")
if m.hexdigest() != signature:
ctx["ok"] = False
return ctx
(user, created) = User.objects.get_or_create(username=username)
user.is_active = True
user.email = email
user.set_password(password)
user.save()
pro = UserProfile()
pro.user = user
pro.save()
p = Polity.objects.get(id=1)
p.members.add(user)
ctx["ok"] = True
ctx["username"] = user.username
ctx["id"] = user.id
return ctx
示例3: create_inactive_user
def create_inactive_user(self, username, email, password,
first_name,
last_name,
career, favorite, gender, age, address, phone, city, state, country, zip,
send_email=True,
profile_callback=None ):
"""
Create a new, inactive ``User``, generate a
``RegistrationProfile`` and email its activation key to the
``User``, returning the new ``User``.
By default, an activation email will be sent to the new
user. To disable this, pass ``send_email=False``.
"""
new_user = User.objects.create_user(username, email, password)
new_user.email = email
new_user.first_name = first_name
new_user.last_name = last_name
new_user.is_active = False
"""
set default user_group when registration
"""
new_user.save()
new_profile = UserProfile(user=new_user,
career=career,
gender=gender,
age=age,
address=address,
phone=phone,
city=city,
state=state,
country=country,
zip=zip
)
new_profile.save()
registration_profile = self.create_profile(new_user)
if send_email:
from django.core.mail import send_mail
current_site = Site.objects.get_current()
subject = render_to_string('registration/activation_email_subject.txt',
{ 'site': current_site })
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
fullname = new_user.last_name + " " + new_user.first_name
message = render_to_string('registration/activation_email.txt',
{ 'activation_key': registration_profile.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'site': current_site,
'fullname': fullname,
})
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
return new_user
示例4: save
def save(self, commit=True):
user = super(SgzUserCreationForm, self).save(commit=False)
user.email = '{}@neverland.cc'.format(user.username)
if commit:
user.save()
profile = UserProfile(user=user)
profile.save()
return user
示例5: login
def login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm,
current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
redirect_to = request.POST.get(redirect_field_name,
request.GET.get(redirect_field_name, ''))
if request.method == "POST":
form = authentication_form(request, data=request.POST)
if form.is_valid():
# Ensure the user-originating redirection url is safe.
if not is_safe_url(url=redirect_to, host=request.get_host()):
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
# Okay, security check complete. Log the user in.
auth_login(request, form.get_user())
# Make sure that profile exists
try:
UserProfile.objects.get(user=request.user)
except UserProfile.DoesNotExist:
profile = UserProfile()
profile.user = request.user
profile.save()
request.session[LANGUAGE_SESSION_KEY] = request.user.userprofile.language
if hasattr(settings, 'SAML_1'): # Is SAML 1.2 support enabled?
if not request.user.userprofile.user_is_verified():
return HttpResponseRedirect(settings.SAML_1['URL'])
if hasattr(settings, 'ICEPIRATE'): # Is IcePirate support enabled?
configure_external_member_db(request.user, create_if_missing=False)
return HttpResponseRedirect(redirect_to)
else:
form = authentication_form(request)
current_site = get_current_site(request)
context = {
'form': form,
redirect_field_name: redirect_to,
'site': current_site,
'site_name': current_site.name,
}
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
示例6: forwards
def forwards(self, orm):
"Whitelist any user who has whitelisted projects."
for project in Project.objects.all():
if project.whitelisted:
# If user doesn't have a profile, create one
try:
profile = project.user.get_profile()
except ObjectDoesNotExist:
profile = UserProfile(user=project.user)
# Whitelist the user's profile
profile.whitelisted = True
profile.save()
示例7: process_request
def process_request(self, request):
if request.user.is_authenticated():
try:
request.session['django_language'] = request.user.get_profile().language
except AttributeError:
# pass
pro = UserProfile()
pro.user = request.user
pro.language = settings.LANGUAGE_CODE
pro.save()
request.session['django_language'] = pro.language
else:
request.session['django_language'] = "is"
示例8: adduser
def adduser(request, ssn=None, name=None, email=None, added=None, username=None):
if ssn is None:
assert(request.GET.get('key') == settings.ICEPIRATE['key'])
# Parse args...
ssn = ssn or request.GET.get('ssn')
name = name or request.GET.get('name')
email = email or request.GET.get('email')
added = added or request.GET.get('added')
username = username or request.GET.get('username')
if added:
added = datetime.strptime(added, '%Y-%m-%d %H:%M:%S')
else:
added = timezone.now()
# Look up all the users that match
users = []
if ssn:
users.extend(User.objects.filter(userprofile__verified_ssn=ssn))
if username:
users.extend(User.objects.filter(username=username))
if email:
users.extend(User.objects.filter(email=email))
# Update or create user
try:
user = users[0]
# Sanity checks...
assert(len([u for u in users if u != user]) == 0)
if user.userprofile.verified_ssn:
assert(user.userprofile.verified_ssn == ssn)
else:
# User exist, is not verified! Just update SSN.
user.userprofile.verified_ssn = ssn
user.userprofile.save()
except IndexError:
# User does not exist. Create user, yay!
if not username:
username = _make_username(name, email)
user = User(username=username, email=email)
user.save()
prof = UserProfile(user=user, verified_ssn=ssn, joined_org=added)
prof.save()
response_data = _icepirate_user_data(user)
response_data.update({
'reset_url': _password_reset_url(user),
'success': True})
return HttpResponse(
json.dumps(response_data), content_type='application/json')
示例9: load_users
def load_users(file):
print '\nimporting users'
for e in json.load(file):
try:
user = User.objects.filter(username=e['username']).get()
except User.DoesNotExist:
user = User.objects.create_user(e['username'], e['email'], 'asdfgh')
user.save()
profile = UserProfile(user=user)
profile.save()
print '.',
sys.stdout.flush()
示例10: search_people
def search_people(self):
qu = self.request.get('q', '')
index = search.Index(name='profileIndex')
query = index.search(qu)
profiles = [UserProfile.get_by_id(int(result.doc_id)) for result in query.results]
return self.render('app/search_people_result.html', profiles=profiles, search_term=qu)
示例11: signup
def signup(request):
from forms import SignupForm
if request.method == 'POST':
# process signup form and create account
form = SignupForm(request.POST)
if form.is_valid():
user = User()
user.username = form.cleaned_data['username']
user.set_password(form.cleaned_data['password1'])
user.email = form.cleaned_data['email']
user.first_name = form.cleaned_data['first_name']
user.last_name = form.cleaned_data['last_name']
user.is_active = True
user.save()
profile = UserProfile(paid_user=True, user=user)
profile.save()
# send a mail with registration details
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
email = EmailMessage('Welcome to Trackpattern',
render_to_string('registration/welcome_mail.txt',
{'username': user.username,
'first_name': user.first_name}),
from_email='[email protected]',
to=[user.email])
email.send()
_out = {'username':user.username,'email':user.email,'first_name':user.first_name,'last_name':user.last_name,'Would you like to sign up to our mailing list to receive free information about analytics and data driven marketing?' : form.cleaned_data['question_1'],'ts':str(datetime.datetime.now())}
emailtoadmin = EmailMessage('Trackpattern - New user has registered',body=json.dumps(_out),from_email="[email protected]",to=["[email protected]",'[email protected]'])
emailtoadmin.send()
#reset = True
# return redirect(
# 'https://trackpattern.chargify.com/h/46549/subscriptions/new/?reference=%s&first_name=%s&last_name=%s&email=%s' % (
# user.id, user.first_name, user.last_name, user.email))
login_user = authenticate(username=user.username, password=form.cleaned_data['password1'])
auth_login(request, login_user)
return redirect('/home/')
else:
form = SignupForm(initial={'question_1': True})
return render_to_response('registration/signup.html',
{'form': form, },
context_instance=RequestContext(request))
示例12: form_valid
def form_valid(self, form):
'''
Creates a new user
'''
team = form.save()
username = form.instance.name.lower().replace(' ', '')
password = password_generator(8)
user = User.objects.create_user(username=username, password=password)
profile = UserProfile()
profile.team = team
profile.user = user
profile.save()
self.request.session['new_user'] = {'username': username, 'password': password}
return super(TeamAddView, self).form_valid(form)
示例13: notify_followers_new_content
def notify_followers_new_content(course):
followers = UserProfile.query(UserProfile.followed_courses == course)
for follower in followers:
notify = Notification(text='Novo conteúdo adicionado %s' %(course.get().title),
profile=follower.key,
ntype='icon-warning-sign'
)
notify.put()
示例14: authenticate
def authenticate(self, oauth_token=None):
if oauth_token is None:
return None
user_info = None
try:
api = TroveAPI(settings.TROVE_APP_KEY, settings.TROVE_APP_SECRET, ["photos"], oauth_token)
user_info = api.get_user_info()
except:
return None
try:
trove_profile = UserProfile.objects.get(trove_user_id=user_info["trove_internal_id"])
return trove_profile.user
except UserProfile.DoesNotExist:
user = User()
if user_info.has_key("trove_username"):
user.username = user_info["trove_username"]
else:
user.username = user_info["trove_internal_id"] # We use the trove internal id if there is no user name
user.first_name = user_info["first_name"]
user.last_name = user_info["last_name"]
user.save()
trove_profile = UserProfile()
trove_profile.trove_user_id = user_info["trove_internal_id"]
trove_profile.trove_access_token_key = oauth_token.key
trove_profile.trove_access_token_secret = oauth_token.secret
trove_profile.user = user
trove_profile.save()
return user
示例15: register
def register(self, request, **cleaned_data):
"""Register a new user, saving the User and UserProfile data."""
user = User()
for field in user._meta.fields:
if field.name in cleaned_data:
setattr(user, field.name, cleaned_data[field.name])
# the password has been validated by the form
user.set_password(cleaned_data["password2"])
user.save()
profile = UserProfile(user=user)
for field in profile._meta.fields:
if field.name in cleaned_data:
setattr(profile, field.name, cleaned_data[field.name])
print "request data: image field"
img_data = request.POST.get("image")
# If none or len 0, means illegal image data
if img_data == None or len(img_data) == 0:
pass
# Decode the image data
img_data = base64.b64decode(img_data)
filename = "%s.png" % uuid.uuid4()
# XXX make the upload path a fixed setting in models, since it's
# reference in two places
upload_path = "data/avatars/%s/" % user.username
upload_abs_path = os.path.join(settings.MEDIA_ROOT, upload_path)
if not os.path.exists(upload_abs_path):
os.makedirs(upload_abs_path)
full_file_name = os.path.join(upload_abs_path, filename)
with open(full_file_name, "wb") as f:
f.write(img_data)
f.close()
profile.image = full_file_name
profile.save()
new_user = authenticate(username=user.username, password=cleaned_data["password2"])
login(request, new_user)
signals.user_activated.send(sender=self.__class__, user=new_user, request=request)
return new_user