def create_profile(**kwargs): if kwargs["created"]: try: get_profile_for_user(kwargs["instance"]) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close()
def __init__(self, *args, **kwargs): super(CustomProfileForm, self).__init__(*args, **kwargs) self._signup = self.instance.id is None user_fields = User._meta.get_all_field_names() if not self._signup: try: self.fields["username"].help_text = ugettext( "Only letters, numbers, dashes or underscores please") except KeyError: pass for field in self.fields: # Make user fields required. if field in user_fields: self.fields[field].required = True # Disable auto-complete for password fields. # Password isn't required for profile update. if field.startswith("password"): self.fields[field].widget.attrs["autocomplete"] = "off" self.fields[field].widget.attrs.pop("required", "") if not self._signup: self.fields[field].required = False if field == "password1": self.fields[field].help_text = ugettext( "Leave blank unless you want " "to change your password") ##Attempt to make the studentid, whilst updating a profile, not required and not autocompleted. if field == "studentid": try: self.fields['studentid'].help_text = ugettext("Je kunt je studentID niet veranderen") except KeyError: pass if not self._signup: self.fields[field].widget.attrs["autocomplete"] = "off" self.fields[field].widget.attrs.pop("required","") self.fields[field].required = False if field == 'beginjaar': self.fields[field].widget.attrs["autocomplete"] = "off" self.fields[field].widget.attrs.pop("required","") self.fields[field].required = False # Add any profile fields to the form. try: profile_fields_form = self.get_profile_fields_form() profile_fields = profile_fields_form().fields self.fields.update(profile_fields) if not self._signup: user_profile = get_profile_for_user(self.instance) ##If this user is going to update his profile, make a veriable called self.STUDENTID (is user later on in this form) self.STUDENTID = getattr(user_profile,'studentid') self.beginjaar = getattr(user_profile,'beginjaar') for field in profile_fields: value = getattr(user_profile, field) # Check for multiple initial values, i.e. a m2m field if isinstance(value, Manager): value = value.all() self.initial[field] = value except ProfileNotConfigured: pass
def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self._signup = self.instance.id is None user_fields = set([f.name for f in User._meta.get_fields()]) _exclude=['address1','address2','city','state','zip_code','phone'] try: self.fields["username"].help_text = ugettext( "Only letters, numbers, dashes or underscores please") except KeyError: pass # Add any profile fields to the form. try: profile_fields_form = self.get_profile_fields_form() profile_fields = profile_fields_form().fields self.fields.update(profile_fields) if not self._signup: user_profile = get_profile_for_user(self.instance) for field in profile_fields: value = getattr(user_profile, field) # Check for multiple initial values, i.e. a m2m field if isinstance(value, Manager): value = value.all() self.initial[field] = value except ProfileNotConfigured: pass for field in self.fields: # Make user fields required. self.fields[field].required = True self.fields[field].widget.attrs['required'] = True # Disable auto-complete for password fields. # Password isn't required for profile update. if field.startswith("password"): self.fields[field].widget.attrs["autocomplete"] = "off" #self.fields[field].widget.attrs.pop("required", "") if field == "password1": self.fields[field].widget.attrs["data-minlength"] = "6" self.fields[field].widget.attrs["data-minlength-error"] = "Must be at least 6 characters" if field == 'password2': self.fields[field].widget.attrs["data-match"] = "#id_password1" self.fields[field].widget.attrs["data-match-error"] = "Whoops, these don't match" if not self._signup: self.fields[field].required = False if field == "password1": self.fields[field].help_text = ugettext( "Leave blank unless you want " "to change your password") if self._signup: if field in _exclude: try: del self.fields[field] except: pass
def save(self, *args, **kwargs): """ Create the new user. If no username is supplied (may be hidden via ``ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS`` or ``ACCOUNTS_NO_USERNAME``), we generate a unique username, so that if profile pages are enabled, we still have something to use as the profile's slug. """ kwargs["commit"] = False user = super(ProfileForm, self).save(*args, **kwargs) try: self.cleaned_data["username"] except KeyError: if not self.instance.username: try: username = ("%(first_name)s %(last_name)s" % self.cleaned_data).strip() except KeyError: username = "" if not username: username = self.cleaned_data["email"].split("@")[0] qs = User.objects.exclude(id=self.instance.id) user.username = unique_slug(qs, "username", slugify(username)) password = self.cleaned_data.get("password1") if password: user.set_password(password) elif self._signup: try: user.set_unusable_password() except AttributeError: # This could happen if using a custom user model that # doesn't inherit from Django's AbstractBaseUser. pass user.save() try: profile = get_profile_for_user(user) profile_form = self.get_profile_fields_form() profile_form(self.data, self.files, instance=profile).save() except ProfileNotConfigured: pass if self._signup: settings.use_editable() if (settings.ACCOUNTS_VERIFICATION_REQUIRED or settings.ACCOUNTS_APPROVAL_REQUIRED): user.is_active = False user.save() else: token = default_token_generator.make_token(user) user = authenticate(uidb36=int_to_base36(user.id), token=token, is_active=True) return user
def profile_fields(user): """ Returns profile fields as a dict for the given user. Used in the profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED`` setting is set to ``True``, and also in the account approval emails sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is set to ``True``. """ fields = OrderedDict() try: profile = get_profile_for_user(user) user_fieldname = get_profile_user_fieldname() exclude = tuple(settings.ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS) for field in profile._meta.get_fields(): if field.name not in ("id", user_fieldname) + exclude: value = getattr(profile, field.name) fields[field.verbose_name.title()] = value except ProfileNotConfigured: pass return list(fields.items())
def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(str(uuid4())[:10]) user.email = self.cleaned_data['email'] #user.clean_email() user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] email_slug = self.cleaned_data["email"].split('@') username = slugify(email_slug[0] + '-' + email_slug[1])[:16] qs = User.objects.exclude(id=self.instance.id) user.username = unique_slug(qs, "username", slugify(username)) user.save() profile = get_profile_for_user(user) profile.membertype = self.cleaned_data['membertype'] profile.organisation = self.cleaned_data['organisation'] profile.save() # if commit: # user.save() return user
def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self._signup = self.instance.id is None user_fields = set([f.name for f in User._meta.get_fields()]) try: self.fields["username"].help_text = ugettext( "Only letters, numbers, dashes or underscores please") except KeyError: pass for field in self.fields: # Make user fields required. if field in user_fields: self.fields[field].required = True # Disable auto-complete for password fields. # Password isn't required for profile update. if field.startswith("password"): self.fields[field].widget.attrs["autocomplete"] = "off" self.fields[field].widget.attrs.pop("required", "") if not self._signup: self.fields[field].required = False if field == "password1": self.fields[field].help_text = ugettext( "Leave blank unless you want " "to change your password") # Add any profile fields to the form. try: profile_fields_form = self.get_profile_fields_form() profile_fields = profile_fields_form().fields self.fields.update(profile_fields) if not self._signup: user_profile = get_profile_for_user(self.instance) for field in profile_fields: value = getattr(user_profile, field) # Check for multiple initial values, i.e. a m2m field if isinstance(value, Manager): value = value.all() self.initial[field] = value except ProfileNotConfigured: pass
def initial_order_data(request, form_class=None): """ Return the initial data for the order form, trying the following in order: - request.POST which is available when moving backward through the checkout steps - current order details in the session which are populated via each checkout step, to support user leaving the checkout entirely and returning - last order made by the user, via user ID or cookie - matching fields on an authenticated user and profile object """ from cartridge.shop.forms import OrderForm initial = {} if request.method == "POST": initial = dict(list(request.POST.items())) try: initial = form_class.preprocess(initial) except (AttributeError, TypeError): # form_class has no preprocess method, or isn't callable. pass # POST on first step won't include the "remember" checkbox if # it isn't checked, and it'll then get an actual value of False # when it's a hidden field - so we give it an empty value when # it's missing from the POST data, to persist it not checked. initial.setdefault("remember", "") # Look for order in current session. if not initial: initial = request.session.get("order", {}) # Look for order in previous session. if not initial: lookup = {} if request.user.is_authenticated(): lookup["user_id"] = request.user.id remembered = request.COOKIES.get("remember", "").split(":") if len(remembered) == 2 and remembered[0] == sign(remembered[1]): lookup["key"] = remembered[1] if lookup: previous = list(Order.objects.filter(**lookup).values())[:1] if len(previous) > 0: initial.update(previous[0]) if not initial and request.user.is_authenticated(): # No previous order data - try and get field values from the # logged in user. Check the profile model before the user model # if it's configured. If the order field name uses one of the # billing/shipping prefixes, also check for it without the # prefix. Finally if a matching attribute is callable, call it # for the field value, to support custom matches on the profile # model. user_models = [request.user] try: user_models.insert(0, get_profile_for_user(request.user)) except ProfileNotConfigured: pass for order_field in OrderForm._meta.fields: check_fields = [order_field] for prefix in ("billing_detail_", "shipping_detail_"): if order_field.startswith(prefix): check_fields.append(order_field.replace(prefix, "", 1)) for user_model in user_models: for check_field in check_fields: user_value = getattr(user_model, check_field, None) if user_value: if callable(user_value): try: user_value = user_value() except TypeError: continue if not initial.get(order_field): initial[order_field] = user_value # Set initial value for "same billing/shipping" based on # whether both sets of address fields are all equal. shipping = lambda f: "shipping_%s" % f[len("billing_"):] if any([ f for f in OrderForm._meta.fields if f.startswith("billing_") and shipping(f) in OrderForm._meta. fields and initial.get(f, "") != initial.get(shipping(f), "") ]): initial["same_billing_shipping"] = False # Never prepopulate discount code. try: del initial["discount_code"] except KeyError: pass return initial
def initial_order_data(request, form_class=None): """ Return the initial data for the order form, trying the following in order: - request.POST which is available when moving backward through the checkout steps - current order details in the session which are populated via each checkout step, to support user leaving the checkout entirely and returning - last order made by the user, via user ID or cookie - matching fields on an authenticated user and profile object """ from cartridge.shop.forms import OrderForm initial = {} if request.method == "POST": initial = dict(list(request.POST.items())) try: initial = form_class.preprocess(initial) except (AttributeError, TypeError): # form_class has no preprocess method, or isn't callable. pass # POST on first step won't include the "remember" checkbox if # it isn't checked, and it'll then get an actual value of False # when it's a hidden field - so we give it an empty value when # it's missing from the POST data, to persist it not checked. initial.setdefault("remember", "") # Look for order in current session. if not initial: initial = request.session.get("order", {}) # Look for order in previous session. if not initial: lookup = {} if request.user.is_authenticated(): lookup["user_id"] = request.user.id remembered = request.COOKIES.get("remember", "").split(":") if len(remembered) == 2 and remembered[0] == sign(remembered[1]): lookup["key"] = remembered[1] if lookup: previous = list(Order.objects.filter(**lookup).values())[:1] if len(previous) > 0: initial.update(previous[0]) if not initial and request.user.is_authenticated(): # No previous order data - try and get field values from the # logged in user. Check the profile model before the user model # if it's configured. If the order field name uses one of the # billing/shipping prefixes, also check for it without the # prefix. Finally if a matching attribute is callable, call it # for the field value, to support custom matches on the profile # model. user_models = [request.user] try: user_models.insert(0, get_profile_for_user(request.user)) except ProfileNotConfigured: pass for order_field in OrderForm._meta.fields: check_fields = [order_field] for prefix in ("billing_detail_", "shipping_detail_"): if order_field.startswith(prefix): check_fields.append(order_field.replace(prefix, "", 1)) for user_model in user_models: for check_field in check_fields: user_value = getattr(user_model, check_field, None) if user_value: if callable(user_value): try: user_value = user_value() except TypeError: continue if not initial.get(order_field): initial[order_field] = user_value # Set initial value for "same billing/shipping" based on # whether both sets of address fields are all equal. shipping = lambda f: "shipping_%s" % f[len("billing_"):] if any([f for f in OrderForm._meta.fields if f.startswith("billing_") and shipping(f) in OrderForm._meta.fields and initial.get(f, "") != initial.get(shipping(f), "")]): initial["same_billing_shipping"] = False # Never prepopulate discount code. try: del initial["discount_code"] except KeyError: pass return initial
def __init__(self, *args, **kwargs): super(ModProfileForm, self).__init__(*args, **kwargs) self._signup = self.instance.id is None user_fields = set([f.name for f in User._meta.get_fields()]) try: self.fields["username"].help_text = ugettext( "Only letters, numbers, dashes or underscores please") except KeyError: pass self.fields['email'].help_text = ugettext( "Not publicly shown") for field in self.fields: # Make user fields required. if field in user_fields: self.fields[field].required = True # Disable auto-complete for password fields. # Password isn't required for profile update. if field.startswith("password"): self.fields[field].widget.attrs["autocomplete"] = "off" self.fields[field].widget.attrs.pop("required", "") if not self._signup: self.fields[field].required = False if field == "password1": self.fields[field].help_text = ugettext( "Leave blank unless you want " "to change your password") # Add any profile fields to the form. # if not self._signup: # exclude fields for standard members try: profile_fields_form = self.get_profile_fields_form() profile_fields = profile_fields_form().fields if self._signup: for field in profile_fields: if field == 'organisation': profile_fields[field].widget.attrs["required"] = True elif field == 'country': profile_fields[field].widget.attrs["required"] = True elif field == 'job_title': profile_fields[field].widget.attrs["required"] = True else: profile_fields[field].widget = forms.MultipleHiddenInput() self.fields.update(profile_fields) if not self._signup: user_profile = get_profile_for_user(self.instance) if user_profile.membertype == 'SM': standard_member_exclude = settings.STANDARD_MEMBER_EXCLUSIONS for f in standard_member_exclude: if f in profile_fields: del profile_fields[f] else: profile_fields['bio'].help_text = ugettext( "Write here the text about yourself and your business as you want it to appear on the IPRA website. There is a maximum character length of 2000.") profile_fields['bio'].widget.attrs["required"] = True profile_fields['photo'].widget = AdvancedFileInput() profile_fields['emailwork'].help_text = ugettext('This will appear in the Member Directory. It may be the same as your login Email above or different.') profile_fields['phone'].help_text = ugettext('Please add preferred phone: mobile or fixed line in International format. (with no gaps)') profile_fields['organisation'].widget.attrs["required"] = True profile_fields['emailalternative'].widget.attrs["required"] = True profile_fields['emailwork'].widget.attrs["required"] = True #profile_fields['nationality'].widget.attrs["required"] = False profile_fields['country'].widget.attrs["required"] = True profile_fields['phone'].widget.attrs["required"] = True profile_fields['phone'].validators = [phone_regex,] #profile_fields['purchased_products'].widget.attrs["required"] = False #profile_fields['purchased_products'].widget = forms.HiddenInput() self.fields.update(profile_fields) for field in profile_fields: value = getattr(user_profile, field) # Check for multiple initial values, i.e. a m2m field if isinstance(value, Manager): value = value.all() self.initial[field] = value except ProfileNotConfigured: pass
def save(self, *args, **kwargs): """ Create the new user. If no username is supplied (may be hidden via ``ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS`` or ``ACCOUNTS_NO_USERNAME``), we generate a unique username, so that if profile pages are enabled, we still have something to use as the profile's slug. """ kwargs["commit"] = False user = super(ModProfileForm, self).save(*args, **kwargs) try: self.cleaned_data["username"] except KeyError: if not self.instance.username: try: email_slug = self.cleaned_data["email"].split('@') username = slugify(email_slug[0] + '-' + email_slug[1])[:16] #username = self.cleaned_data["email"].split("@")[0] except KeyError: username = "" if not username: #username = self.cleaned_data["email"].split("@")[0] email_slug = self.cleaned_data["email"].split('@') username = slugify(email_slug[0] + '-' + email_slug[1])[:16] qs = User.objects.exclude(id=self.instance.id) user.username = unique_slug(qs, "username", slugify(username)) password = self.cleaned_data.get("password1") if password: user.set_password(password) elif self._signup: try: user.set_unusable_password() except AttributeError: # This could happen if using a custom user model that # doesn't inherit from Django's AbstractBaseUser. pass user.save() try: profile = get_profile_for_user(user) profile_form = self.get_profile_fields_form() profile_form(self.data, self.files, instance=profile).save() except ProfileNotConfigured: pass if self._signup: ## create SubscriberEmailAddress object for the group "members" ## so we can keep email address on record in future # g = EmailGroup.objects.get_or_create(title="Sign Ups")[0] # sub = SubscriberEmailAddress(sub_email=g, # email=self.cleaned_data["email"], # firstname=self.cleaned_data["first_name"], # lastname=self.cleaned_data["last_name"], # source='Website' # ) # sub.save() profile.membertype = 'SU' profile.save() g = EmailGroup.objects.get_or_create(title='Sign Ups')[0] profile.contacttype.add(g) ############################################### if (settings.ACCOUNTS_VERIFICATION_REQUIRED or settings.ACCOUNTS_APPROVAL_REQUIRED): user.is_active = False user.save() else: token = default_token_generator.make_token(user) user = authenticate(uidb36=int_to_base36(user.id), token=token, is_active=True) # else: # if not user.is_staff: # sub = SubscriberEmailAddress.objects.get(email=user.email) # if self.cleaned_data["organisation"]: # sub.organisation = self.cleaned_data["organisation"] # if self.cleaned_data["nationality"]: # sub.country = self.cleaned_data["nationality"] # sub.save() return user
def create_user(data,membertype): #username = slugify(data['First name']) + '-' + slugify(data['Last name']) email_slug = data['e-Mail'].split('@') username = slugify(email_slug[0] + '-' + email_slug[1])[:16] #qs = User.objects.exclude(id=self.instance.id) #username = unique_slug(qs, "username", slugify(username)) # username = slugify(data['e-Mail']) + '-' + slugify(data['Last name']) user, created = User.objects.get_or_create(first_name=data['First name'], last_name=data['Last name'], email=data['e-Mail'], username=username, ) password = User.objects.make_random_password() user.set_password(password) profile = get_profile_for_user(user) if data['Organization'] != 0: profile.organisation = data['Organization'] if data['Personal Email'] != 0: profile.emailwork = data['Personal Email'] if data['Phone'] != 0: profile.phone = data['Phone'] if data['Website'] != 0: profile.website = data['Website'] if data['Short Bio'] != 0: profile.bio = data['Short Bio'] profile.membertype = membertype profile.paid = True try: date_object = datetime.strptime(data['Renewal due'], '%m/%d/%Y %H:%M:%S') date = date_object.replace(tzinfo=timezone('GMT')) profile.expires = date except Exception as e: pass try: date_object = datetime.strptime(data['Renewal date last changed'], '%m/%d/%Y %H:%M:%S') date = date_object.replace(tzinfo=timezone('GMT')) profile.paidfrom = date except Exception as e: self.stdout.write(e) pass try: date_object = datetime.strptime(data['Member since'], '%m/%d/%Y %H:%M:%S') date = date_object.replace(tzinfo=timezone('GMT')) # user.date_joined = date membersince = date except Exception as e: membersince = djangodatetime.now() self.stdout.write(e) pass user.save() profile.save() if membertype == 'PM': g = EmailGroup.objects.get_or_create(title='Members')[0] gp = EmailGroup.objects.get_or_create(title='Pro Members')[0] profile.contacttype.add(g,gp) if membertype == 'SM': g = EmailGroup.objects.get_or_create(title='Members')[0] gp = EmailGroup.objects.get_or_create(title='Standard Members')[0] profile.contacttype.add(g,gp)
def get_avatar_path(user): return get_profile_for_user(user).avatar.url