• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.Profile类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中users.models.Profile的典型用法代码示例。如果您正苦于以下问题:Python Profile类的具体用法?Python Profile怎么用?Python Profile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Profile类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_user_profile

def get_user_profile(user):
    """ Returns user profile. Creates one if needed """
    if not (user and user.is_authenticated()):
        return None
    pr = cache.get("users_profile:auth_user=%s" % user.id, None)
    if pr:
        return pr
    pr = get_profile_by_email_or_phone(user.username)
    if not pr:
        pr = Profile.objects.filter(user=user).order_by("id")[:2]
        if len(pr) > 1:
            fb_log.info("Multiple profiles for user: %s" % user.username)
        if pr:
            pr = pr[0]
        if not pr:
            pr = Profile(user=user)
            pr.created_on = datetime.now()
            pr.save()
            if is_valid_email(user.username):
                try:
                    email = Email(email=user.username, user=pr, type="primary")
                    email.save()
                except:
                    pass
            if is_valid_mobile(user.username):
                try:
                    phone = Phone(phone - user.username, user=pr, type="primary")
                    phone.save()
                except:
                    pass
    cache.set("users_profile:auth_user=%s" % user.id, pr)
    return pr
开发者ID:,项目名称:,代码行数:32,代码来源:


示例2: addUser

def addUser(request):
    form = UserForm(request.POST)
    
    if form.is_valid():
        try:
            with transaction.atomic():
                enterprise = Enterprise()
                enterprise.save()
                request.session['idEnterprise'] = enterprise.id;
                
                location= Location(enterprise=enterprise, lat=0, lng=0, name='Main Office')
                location.save()
                
                user = User(location = location, email=form.cleaned_data['email'], 
                        password=form.cleaned_data['password'])
                user.save()
                request.session['idUser'] = user.id;
                
                profile = Profile(user = user, role="Administrator")
                profile.save()
                
                return render(request, 'users/dashboard.html')
                
        except Exception as e:
            print(e)
            messages.error(request, 'Sorry, Internal Error')
                
    else:
        messages.error(request, 'Please fill the form')
        return HttpResponseRedirect('/signup')
开发者ID:edramos,项目名称:path00,代码行数:30,代码来源:views.py


示例3: handle

 def handle(self, *args, **options):
     for user in User.objects.all():
         if Profile.objects.filter(user=user).count() == 0:
             print "No profile for user: %s" % (user,)
             new_profile = Profile(user=user, activation_key=generate_activation_key(user.username))
             new_profile.save()
             print "Created new profile for username: %s" % (user.username,)
开发者ID:fjern,项目名称:piosenka,代码行数:7,代码来源:create_missing_profiles.py


示例4: register

def register(request):
	if request.method == 'POST' and not request.user.is_authenticated():
		username = request.POST.get('username')
		email = request.POST.get('email')
		password = request.POST.get('password')
		confirm = request.POST.get('confirm')
		
		try:
			existing_user = User.objects.get(username=username)
			context = RequestContext(request, {'register_message': 'Username {} already exists.'.format(username)})
			return render(request, 'home.html', context)
		except ObjectDoesNotExist:
			pass
		
		try:
			existing_user = User.objects.get(email=email)
			context = RequestContext(request, {'register_message': 'E-mail {} already exists.'.format(email)})
			return render(request, 'home.html', context)
		except ObjectDoesNotExist:
			pass
			
		if password == confirm:
			new_user = User.objects.create_user(username, email=email, password=password)
			new_profile = Profile()
			new_profile.user = new_user
			new_profile.save()
			
			return redirect('home')
		else:
			context = RequestContext(request, {'register_message': 'Passwords do not match.'.format(email)})
			return render(request, 'home.html', context)
			
	else:
		return redirect('home')
开发者ID:adzierzanowski,项目名称:pinboard,代码行数:34,代码来源:views.py


示例5: create_user

def create_user(username, email_id="", password=None, first_name="", last_name=""):
    """ This function called for new user sign up on p. interface. Thus username should be a valid phone number."""
    usr = None
    profile = None
    if not username:
        return usr, profile
    username = username.strip()
    is_type = "id"
    if is_valid_mobile(username):
        is_type = "mobile"
        try:
            usr = User(username=username, email="")
            if password is None or password == "":
                # use set_unusable_password to allow user to set his password in future
                usr.set_unusable_password()
            else:
                usr.set_password(password)
            if first_name:
                usr.first_name = first_name
            if last_name:
                usr.last_name = last_name
            usr.save()
            profile = Profile(
                user=usr, created_on=datetime.now(), primary_phone="", primary_email="", secondary_email=""
            )
            if first_name and last_name:
                profile.full_name = "%s %s" % (first_name, last_name)
            profile.save()
            phone = Phone(user=profile, phone=username, type="primary")
            phone.is_verified = True
            phone.verified_on = datetime.now()
            phone.save()
        except Exception, e:
            log.exception("Error create_user username: %s  Exception: %s" % (username, repr(e)))
            return None, None
开发者ID:,项目名称:,代码行数:35,代码来源:


示例6: profile

def profile(user, **kwargs):
    """Return a saved profile for a given user."""
    defaults = {"user": user}
    defaults.update(kwargs)

    p = Profile(**defaults)
    p.save()
    return p
开发者ID:ryansnyder,项目名称:spark,代码行数:8,代码来源:__init__.py


示例7: _create_user

def _create_user(username, rolename, data=None):
  if data is None:
    data = {}
  role = Role.select().where(Role.name==rolename).get()
  Profile.create(username=username, email=username+'@srv.pl', role=role,
                 description=data.get('description', 'User ' + username + ' description'),
                 title=data.get('title', 'User ' + username + ' title'),
                 location=data.get('location', 'User ' + username + ' location'))
开发者ID:vooydzig,项目名称:bottle-forum,代码行数:8,代码来源:utils.py


示例8: form_valid

 def form_valid(self, form):
     # profile 따로 저장해줌
     # 꼼수인데 방법이 되네요
     user = form.save()
     p = Profile()
     p.user = user
     p.save()
     messages.success(self.request, '계정이 생성되었습니다')
     return super(CreateUser, self).form_valid(form)
开发者ID:sebatyler,项目名称:django-bookmark,代码行数:9,代码来源:views.py


示例9: profile

def profile(user, **kwargs):
    """Return a saved profile for a given user."""
    defaults = {'user': user, 'name': 'Test K. User', 'bio': 'Some bio.',
                'website': 'http://support.mozilla.com',
                'timezone': None, 'country': 'US', 'city': 'Mountain View'}
    defaults.update(kwargs)

    p = Profile(**defaults)
    p.save()
    return p
开发者ID:MechanisM,项目名称:kitsune,代码行数:10,代码来源:__init__.py


示例10: signup

def signup(request):
    from auth.models import User
    from auth import load_backend, login
    from users.models import Profile, EmailVerify
    from market_buy.forms import BuyerForm
    
    form = BuyerForm(request.POST or None)
    if form.is_valid():
        """ Generate Auth User """
        user = User.objects.create_user(form.cleaned_data["username"],
                                        form.cleaned_data["email"], 
                                        form.cleaned_data["password1"])
        
        user.first_name = form.cleaned_data["first_name"]
        user.last_name = form.cleaned_data["last_name"]
        user.is_active = False
        user.save()
        
        """ Set profile """
        profile = Profile(user=user)
        profile.save()

        """ Send mail to confirm account """
        email_verify = EmailVerify(user=user, user_activation=True)
        code = email_verify.generate_code()
        email_verify.save()
        
        # TODO: remove this
        send_mail_account_confirmation(user, email_verify.code, request.marketplace)        
        
#        return HttpResponseRedirect(reverse('confirmemail', args=[code]))
#        for backend in settings.AUTHENTICATION_BACKENDS:
#            if user == load_backend(backend).get_user(user.pk):
#                user.backend = backend
#                break
#        if hasattr(user, 'backend'):
#            login(request, user)
        
        if request.session.get('sell_signup',False):
            request.flash['message'] = _("<h5>Please check your email and confirm your account to start selling...</h5>")
            request.flash['severity'] = "success"
            return HttpResponseRedirect(reverse('market_sell_signup'))
        else:
            request.flash['message'] = _("<h5>Please check your email and confirm your account. Once confirmed you can Buy or Sell on GreatCoins.com</h5>")
            request.flash['severity'] = "success"
            return HttpResponseRedirect(reverse('market_home'))
    else:
        #request.method == GET
        if request.GET.has_key('sell_signup'):
            request.session['sell_signup'] = request.GET.get('sell_signup','') == '1'

    return render_to_response('%s/buy/register.html'% request.marketplace.template_prefix, 
                              {'form': form},
                              RequestContext(request))
开发者ID:Bobby1994,项目名称:CollectorCity-Market-Place,代码行数:54,代码来源:views.py


示例11: create_tables

def create_tables():
  database.connect()
  Category.drop_table(fail_silently=True)
  Thread.drop_table(fail_silently=True)
  Post.drop_table(fail_silently=True)
  Role.drop_table(fail_silently=True)
  Profile.drop_table(fail_silently=True)
  database.create_tables([Category, Thread, Post, Profile, Role])
  database.close()

  if settings.DEBUG:
    setup_temp_data()
开发者ID:vooydzig,项目名称:bottle-forum,代码行数:12,代码来源:utils.py


示例12: attach_fb

def attach_fb(request):
    if request.method == "POST":
        data = request.POST
        facebookid = data["id"]
        email = data["email"]
        first_name = data["first_name"]
        last_name = data["last_name"]

        user, profile = None, None
        u_email = None
        try:
            u_email = UserEmail.objects.get(email=email)
            profile = u_email.user
            user = profile.user
        except UserEmail.DoesNotExist:
            try:
                user = User.objects.get(Q(email=email) | Q(username=email))
            except User.DoesNotExist:
                user = User.objects.create_user(email, email, None)
                user.first_name = first_name
                user.last_name = last_name
                user.save()
        if not user.first_name:
            user.first_name = first_name
            user.save()
        if not user.last_name:
            user.last_name = last_name
            user.save()

        try:
            profile = Profile.objects.get(user=user)
        except Profile.DoesNotExist:
            profile = Profile(user=user, full_name="%s %s" % (first_name, last_name))
        # if not profile.full_name: overwrite facebook name
        profile.full_name = "%s %s" % (first_name, last_name)
        profile.facebook = facebookid
        profile.save()
        if not u_email:
            u_email = UserEmail(email=email, user=profile, type="subscription")
            u_email.save()
        if request.user:
            auth.logout(request)
            request.session.flush()
        user = auth.authenticate(facebook_user=user, **dict(request=request))
        request.session["logged_through_facebook"] = True
        if user:
            request.session["atg_username"] = user.username
            set_logged_in_user(request, user)
            log.info("FACEBOOK USER LOGGED IN: %s" % user)
            return HttpResponse("OK")
    else:
        return HttpResponse("OK")
    return HttpResponse("FAILED")
开发者ID:,项目名称:,代码行数:53,代码来源:


示例13: register

 def register(self, request, **cleaned_data):
     """Custom registration view.
     """
     print('Starting registration')
     print(cleaned_data)
     u = User.objects.create_user(
         cleaned_data['username'],
         '',
         cleaned_data['password1'])
     p = Profile()
     p.user = u
     p.save()
     messages.success(self.request,
                      'Thank you for registering. Now you can login.')
开发者ID:timbarnes,项目名称:QandAWeb,代码行数:14,代码来源:views.py


示例14: home

def home(request):
    if request.user.is_authenticated():
        return render(request, 'dashboard.html')
    else:
        if request.method == 'POST':
            form = LoginForm(request.POST)
            if form.is_valid():
                user = authenticate(username=request.POST["username"], password=request.POST["password"])
                if user:
                    auth.login(request, user)
                    profile = Profile(user=user, last_login_source=request.META["REMOTE_ADDR"])
                    profile.save()
                    return render(request, 'dashboard.html')
        return render(request, 'index.html')
开发者ID:taba84,项目名称:task_manager,代码行数:14,代码来源:views.py


示例15: profile

def profile(**kwargs):
    """Return a saved profile for a given user."""
    defaults = {'name': 'Test K. User', 'bio': 'Some bio.',
                'website': 'http://support.mozilla.com',
                'timezone': None, 'country': 'US', 'city': 'Mountain View',
                'locale': 'en-US'}
    if 'user' not in kwargs:
        u = user(save=True)
        defaults['user'] = u
    defaults.update(kwargs)

    p = Profile(**defaults)
    p.save()
    return p
开发者ID:ejean555,项目名称:kitsune,代码行数:14,代码来源:__init__.py


示例16: registrar_usuario

def registrar_usuario(request):
    if request.POST:
        f=RegistrationForm(request.POST)
        if f.errors:
            messages.error(request, 'El formulario contiene errores')
            return render_to_response("registro_caja.html", {'form':f}, RequestContext(request))
        else:
            data = f.cleaned_data
            user=User()
            user.username=data["username"]
            passwd=get_pronounceable_password(1,2)
            user.set_password(passwd)
            user.email = data['email']
            user.first_name = data['first_name']
            user.last_name = data['last_name']
            user.save()

            profile = Profile()
            profile.user=user
            profile.telefono = data['phone_number']
            profile.celular = data['cellphone']
            profile.direccion = data['address']
            profile.tipo = CLIENTE
            profile.save()
            
            messages.success(request, 'Usuario creado con exito')

            return render_to_response('mostrar_usuario.html', {'user':user,'passwd':passwd}, RequestContext(request))

    else:
        f=RegistrationForm()

    return render_to_response("registro_caja.html", {'form':f}, RequestContext(request))
开发者ID:job-s,项目名称:n-mat,代码行数:33,代码来源:views.py


示例17: create_profile

def create_profile(sender, instance, created, using, *args, **kwargs):
    """
    Crea el perfil de usuario cuando se crea un usuario.
    """
    from users.models import Profile

    if created:
        try:
            sp_id = transaction.savepoint()
            profile = Profile(user=instance, username=instance.username)
            profile.save()
            transaction.savepoint_commit(sp_id)
        except Exception, e:
            logging.error('ERROR: %s ' % e)
            transaction.savepoint_rollback(sp_id)
开发者ID:mandlaweb,项目名称:Zero-Users,代码行数:15,代码来源:listeners.py


示例18: setUp

    def setUp(self):
        # create store owner user and profile
        self.owner = User.objects.create_user("test-owner", "[email protected]", "test-owner")
        owner_profile = Profile(user=self.owner)
        owner_profile.save()

        # create a marketplace
        self.marketplace = MarketPlace(name="greatcoins", title="greatcoins", slug="greatcoins", 
                                       template_prefix="greatcoins", base_domain="greatcoins.com")
        self.marketplace.save()

        # create a shop
        self.shop = Shop(marketplace=self.marketplace, admin=self.owner, name="test_shop")
        self.shop.save()

        # create a Preference and SubscriptionPlan to shop
        Preference(shop=self.shop).save()
        self.shop.update()
        plan = SubscriptionPlan(plan_id=1,
                         marketplace=self.marketplace,
                         trial_period=True,
                         total_store_revenue=1000,
                         concurrent_store_items=1000)
        plan.save()
        Subscription(owner=owner_profile, plan=plan).save()

        # create marketplace categories and sub-categories
        self.category = MarketCategory(marketplace=self.marketplace, name="Category")
        self.category.save()
        self.subcategory = MarketSubCategory(marketplace=self.marketplace, parent=self.category, name="SubCategory")
        self.subcategory.save()

        # create a user, profile and shipping data
        self.user = User.objects.create_user("test-user", "[email protected]", "test-user")
        Profile(user=self.user).save()
        shippingdata = ShippingData(first_name='User',
                                    last_name='Buyer',
                                    street_address="Calle 54",
                                    city="La Plata",
                                    state="Buenos Aires",
                                    zip="1900",
                                    country="AR")
        shippingdata.save()

        # create a shopping cart
        self.cart = Cart(shop=self.shop, bidder=self.user)
        self.cart.shippingdata = shippingdata
        self.cart.save()
开发者ID:HengWang,项目名称:CollectorCity-Market-Place,代码行数:48,代码来源:tests.py


示例19: create_temp_posts

def create_temp_posts():
  with open('fixtures/posts.json') as f:
    posts = json.load(f)
    for p in posts:
      t = Thread.select().where(Thread.id==p['thread']).get()
      u = Profile.select().where(Profile.id==p['author']).get()
      Post.create(author=u, thread=t, body=p['body'], is_sticky=[['is_sticky']])
开发者ID:vooydzig,项目名称:bottle-forum,代码行数:7,代码来源:utils.py


示例20: get_agent

 def get_agent(self, agent_name):
     try:
         usr = User.objects.get(username=agent_name)
         p = usr.get_profile()
         return p
     except User.DoesNotExist:
         try:
             usr = User.objects.create_user(agent_name, '%[email protected]' % agent_name)
             usr.save()
             p = Profile(user=usr, primary_phone=agent_name)
             p.created_on = datetime.datetime.now()
             p.save()
             return p
         except Exception, e:
             log.error('Error creating agent %s' % repr(e))
             return None
开发者ID:,项目名称:,代码行数:16,代码来源:



注:本文中的users.models.Profile类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Setting类代码示例发布时间:2022-05-27
下一篇:
Python models.create_profile函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap