本文整理汇总了Python中mezzanine.utils.urls.slugify函数的典型用法代码示例。如果您正苦于以下问题:Python slugify函数的具体用法?Python slugify怎么用?Python slugify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了slugify函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: entries_view
def entries_view(self, request, form_id):
"""
Displays the form entries in a HTML table with option to
export as CSV file.
"""
if request.POST.get("back"):
change_url = admin_url(Form, "change", form_id)
return HttpResponseRedirect(change_url)
form = get_object_or_404(Form, id=form_id)
entries_form = EntriesForm(form, request, request.POST or None)
delete_entries_perm = "%s.delete_formentry" % FormEntry._meta.app_label
can_delete_entries = request.user.has_perm(delete_entries_perm)
submitted = entries_form.is_valid()
if submitted:
if request.POST.get("export"):
response = HttpResponse(content_type="text/csv")
timestamp = slugify(datetime.now().ctime())
fname = "%s-%s.csv" % (slugify(form.title), timestamp)
header = "attachment; filename=%s" % fname
response["Content-Disposition"] = header
queue = StringIO()
delimiter = settings.FORMS_CSV_DELIMITER
try:
csv = writer(queue, delimiter=delimiter)
writerow = csv.writerow
except TypeError:
queue = BytesIO()
delimiter = bytes(delimiter, encoding="utf-8")
csv = writer(queue, delimiter=delimiter)
writerow = lambda row: csv.writerow([c.encode("utf-8")
if hasattr(c, "encode") else c for c in row])
writerow(entries_form.columns())
for row in entries_form.rows(csv=True):
writerow(row)
data = queue.getvalue()
response.write(data)
return response
elif request.POST.get("delete") and can_delete_entries:
selected = request.POST.getlist("selected")
if selected:
entries = FormEntry.objects.filter(id__in=selected)
count = entries.count()
if count > 0:
entries.delete()
message = ungettext("1 entry deleted",
"%(count)s entries deleted", count)
info(request, message % {"count": count})
template = "admin/clubhouse_forms/entries.html"
context = {"title": _("View Entries"), "entries_form": entries_form,
"opts": self.model._meta, "original": form,
"can_delete_entries": can_delete_entries,
"submitted": submitted}
return render_to_response(template, context, RequestContext(request))
开发者ID:chazmead,项目名称:django-clubhouse,代码行数:53,代码来源:admin.py
示例2: test_page_slug_has_correct_lang
def test_page_slug_has_correct_lang(self):
"""
Test that slug generation is done for the default language and
not the active one.
"""
from collections import OrderedDict
from django.utils.translation import get_language, activate
from mezzanine.utils.urls import slugify
default_language = get_language()
code_list = OrderedDict(settings.LANGUAGES)
del code_list[default_language]
title_1 = "Title firt language"
title_2 = "Title second language"
page, _ = RichTextPage.objects.get_or_create(title=title_1)
for code in code_list:
try:
activate(code)
except:
pass
else:
break
# No valid language found
page.delete()
return
page.title = title_2
page.save()
self.assertEqual(page.get_slug(), slugify(title_1))
self.assertEqual(page.title, title_2)
activate(default_language)
self.assertEqual(page.title, title_1)
page.delete()
开发者ID:ctrengove,项目名称:mezzanine,代码行数:32,代码来源:tests.py
示例3: export_view
def export_view(self, request, form_id):
"""
Exports the form entries in either a HTML table or CSV file.
"""
if request.POST.get("back"):
change_url = admin_url(Form, "change", form_id)
return HttpResponseRedirect(change_url)
form = get_object_or_404(Form, id=form_id)
export_form = ExportForm(form, request, request.POST or None)
submitted = export_form.is_valid()
if submitted:
if request.POST.get("export"):
response = HttpResponse(mimetype="text/csv")
timestamp = slugify(datetime.now().ctime())
fname = "%s-%s.csv" % (form.slug, timestamp)
header = "attachment; filename=%s" % fname
response["Content-Disposition"] = header
csv = writer(response, delimiter=settings.FORMS_CSV_DELIMITER)
csv.writerow(export_form.columns())
for rows in export_form.rows():
csv.writerow(rows)
return response
template = "admin/forms/export.html"
context = {"title": _("Export Entries"), "export_form": export_form,
"submitted": submitted}
return render_to_response(template, context, RequestContext(request))
开发者ID:CCLab,项目名称:websites,代码行数:26,代码来源:admin.py
示例4: get_slug
def get_slug(cv_dict):
"""
emulates the cv model get_slug function with the dict data
"""
return slugify(u"{0}-{1}-{2}".format(cv_dict["Given First Name"],
cv_dict.get("Given Middle Name", ''),
cv_dict.get("Surname", '')))
开发者ID:NyakudyaA,项目名称:core,代码行数:7,代码来源:cvs_load.py
示例5: save
def save(self, *args, **kwargs):
kwargs["commit"] = False
user = super(AddUserForm, self).save(*args, **kwargs)
try:
self.cleaned_data["username"]
except KeyError:
if not self.instance.username:
username = "%(first_name)s %(last_name)s" % self.cleaned_data
if not username.strip():
username = self.cleaned_data["email"].split("@")[0]
qs = User.objects.exclude(id=self.instance.id) # @UndefinedVariable PyDev limitation ("exclude")
user.username = unique_slug(qs, "username", slugify(username))
password = self.cleaned_data.get("password1")
if password:
user.set_password(password)
user.save()
# Save profile model.
ProfileFieldsForm(self.data, self.files, instance=user.profile).save()
settings.use_editable()
#if (settings.ACCOUNTS_VERIFICATION_REQUIRED or
# settings.ACCOUNTS_APPROVAL_REQUIRED):
# user.is_active = False
# user.save()
return user
开发者ID:hderaps,项目名称:bccf,代码行数:25,代码来源:forms.py
示例6: render
def render(self, context):
if self.is_variable:
real_slug = template.Variable(self.slug).resolve(context)
else:
real_slug = self.slug
if isinstance(self.template_name, template.Variable):
real_template = self.template_name.resolve(context)
else:
real_template = self.template_name
real_title = real_slug
real_slug = slugify(real_slug)
# Eventually we want to pass the whole context to the template so that
# users have the maximum of flexibility of what to do in there.
if self.with_template:
new_ctx = {}
new_ctx.update(context.flatten())
try:
flatblock = None
if self.cache_time != 0:
cache_key = settings.MEZZANINE_BLOCKS_CACHE_PREFIX + real_slug
flatblock = cache.get(cache_key)
if flatblock is None:
if self.is_rich:
_klass = RichBlock
elif self.is_image:
_klass = ImageBlock
else:
_klass = Block
flatblock, created = _klass.objects.get_or_create(
slug=real_slug,
defaults = {'title': real_title}
)
if self.cache_time != 0:
if self.cache_time is None or self.cache_time == 'None':
logger.debug("Caching %s for the cache's default timeout"
% (real_slug,))
cache.set(cache_key, flatblock)
else:
logger.debug("Caching %s for %s seconds" % (real_slug,
str(self.cache_time)))
cache.set(cache_key, flatblock, int(self.cache_time))
else:
logger.debug("Don't cache %s" % (real_slug,))
if self.with_template:
tmpl = loader.get_template(real_template)
new_ctx.update({'flatblock':flatblock})
return tmpl.render(new_ctx)
else:
return flatblock.content
except Block.DoesNotExist:
return ''
开发者ID:karalics,项目名称:mezzanine-blocks,代码行数:59,代码来源:block_tags.py
示例7: get_slug
def get_slug(self):
"""
Recursively build the slug from the chain of parents.
"""
slug = slugify(self.title)
if self.parent is not None:
return "%s/%s" % (self.parent.slug, slug)
return slug
开发者ID:tuotantotalous,项目名称:mezzanine,代码行数:8,代码来源:models.py
示例8: save
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
开发者ID:MariusCC,项目名称:mezzanine,代码行数:55,代码来源:forms.py
示例9: get_slug
def get_slug(self):
"""
Allows subclasses to implement their own slug creation logic.
"""
attr = "title"
if settings.USE_MODELTRANSLATION:
from modeltranslation.utils import build_localized_fieldname
attr = build_localized_fieldname(attr, settings.LANGUAGE_CODE)
# Get self.title_xx where xx is the default language, if any.
# Get self.title otherwise.
return slugify(getattr(self, attr, None) or self.title)
开发者ID:Kniyl,项目名称:mezzanine,代码行数:11,代码来源:models.py
示例10: save
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
开发者ID:skru,项目名称:cartridge_app,代码行数:21,代码来源:forms.py
示例11: handle
def handle(self, *args, **options):
try:
with open('students2.json') as data_file:
data = json.load(data_file)
member_group = EmailGroup.objects.get_or_create(title='Standard Members')[0]
student_group = EmailGroup.objects.get_or_create(title='Students temporary')[0]
marketing_group = EmailGroup.objects.get_or_create(title='Marketing')[0]
for row in data:
print(row['name'])
user, created = User.objects.get_or_create(email=row['email'])
if created:
email_slug = row["email"].split('@')
username = slugify(email_slug[0] + '-' + email_slug[1])[:16]
qs = User.objects.exclude(id=user.id)
user.username = unique_slug(qs, "username", slugify(username))
split_name = row['name'].split(' ',1)
print(split_name)
user.first_name = split_name[0]
user.last_name = split_name[1]
#profile = get_profile_for_user(user)
user.profile.membertype = 'SM'
user.profile.paid = True
user.profile.paidfrom = timezone.now()
user.profile.expires = timezone.now() + timezone.timedelta(days=366)
user.profile.contacttype.add(member_group,student_group,marketing_group)
user.profile.save()
user.save()
else:
print('already in ', user)
except Exception as e:
print(e)
开发者ID:skru,项目名称:cartridge_app,代码行数:40,代码来源:students.py
示例12: save
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:
user.set_unusable_password()
user.save()
# save profile
profile, created = Profile.objects.get_or_create(user=user)
profile_form = self.get_profile_fields_form()
profile_form(self.data, self.files, instance=profile).save()
# save lol account
lol_account, created = LolAccount.objects.get_or_create(user=user)
lolaccount_form = LolAccountFieldsForm
lolaccount_form(self.data, self.files, instance=lol_account).save()
if self._signup:
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
开发者ID:Nick011,项目名称:lolsteak,代码行数:52,代码来源:forms.py
示例13: clean_username
def clean_username(self):
"""
Ensure the username doesn't exist or contain invalid chars.
We limit it to slugifiable chars since it's used as the slug
for the user's profile view.
"""
username = self.cleaned_data.get("username")
if username != slugify(username):
raise forms.ValidationError(_("Username can only contain letters, " "numbers, dashes or underscores."))
try:
User.objects.exclude(id=self.instance.id).get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(_("This username is already registered"))
开发者ID:chris-robison,项目名称:mezzanine,代码行数:14,代码来源:forms.py
示例14: clean_username
def clean_username(self):
"""
Ensure the username doesn't exist or contain invalid chars.
We limit it to slugifiable chars since it's used as the slug
for the user's profile view.
"""
username = self.cleaned_data.get("username")
if username.lower() != slugify(username).lower():
raise forms.ValidationError("Username can only contain letters, "
"numbers, dashes or underscores.")
lookup = {"username__iexact": username}
try:
User.objects.exclude(id=self.instance.id).get(**lookup) # @UndefinedVariable PyDev limitation ("exclude")
except User.DoesNotExist:
return username
raise forms.ValidationError("This username is already registered")
开发者ID:hderaps,项目名称:bccf,代码行数:16,代码来源:forms.py
示例15: return_formentry
def return_formentry(slug):
""" take a form slug, possibly other filter conditions, return form entry
results. """
# A 'form' is the description and fields for a form.
print >>sys.stderr,"slug:%r" % slug
single_form = Form.objects.get(slug=slug)
# A 'form entry' represents an instance of filling out a form.
# this formentry_list contains all of the filled out forms with the
# passed in slug.
formentry_list=FormEntry.objects.filter(form_id=single_form.id)
label_list = [ ]
field_list = Field.objects.filter(form_id=single_form.id)
fieldsByID = {f.id:f for f in field_list}
#for field in fieldsByID:
# print "field_id: %r field: %r" % (field, fieldsByID[field] )
entrylist = [ ]
entrydictlist = [ ]
# I want a list of formentries?
# now I build a list of data entries
for formentry in formentry_list:
entry={}
entrydict={}
fieldentry_list = FieldEntry.objects.filter(entry_id=formentry.id)
for fieldentry in fieldentry_list:
fieldid =fieldentry.field_id
slug = slugify(fieldsByID[fieldentry.field_id])
value =fieldentry.value
#print "try label:%s slug:%s value:%s " % (fieldsByID[fieldentry.field_id] , slug, fieldentry.value)
entry[fieldsByID[fieldentry.field_id]] = fieldentry
entrydict[slug] = value
entrylist.append(entry)
entrydictlist.append(entrydict)
rv = {}
rv['slug'] = slug
rv['fieldsByID'] = fieldsByID
rv['entrylist']=entrylist
rv['entrydictlist']=entrydictlist
return rv
开发者ID:MrNice,项目名称:hir,代码行数:45,代码来源:views.py
示例16: save
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:
username = "%(first_name)s %(last_name)s" % self.cleaned_data
if not username.strip():
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)
user.save()
# Save profile model.
if self._has_profile:
try:
profile = user.get_profile()
except Profile.DoesNotExist:
profile = Profile(user=user)
profile_fields_form = self.get_profile_fields_form()
profile_fields_form(self.data, self.files, instance=profile).save()
if self._signup:
settings.use_editable()
if (settings.ACCOUNTS_VERIFICATION_REQUIRED or
settings.ACCOUNTS_APPROVAL_REQUIRED):
user.is_active = False
user.save()
else:
user = authenticate(username=user.username,
password=password, is_active=True)
return user
开发者ID:AdnanHodzic,项目名称:mezzanine,代码行数:44,代码来源:forms.py
示例17: compare
def compare(request):
form = DifferenceForm(auto_id=True)
if request.method == "POST":
form = DifferenceForm(request.POST, auto_id=True)
if form.is_valid():
sub_one_word = form.cleaned_data['subject_one'].lower()
sub_two_word = form.cleaned_data['subject_two'].lower()
sub_one_word_slugged = slugify(sub_one_word)
sub_two_word_slugged = slugify(sub_two_word)
# FORCE WORDS TO BE IN CERTAIN ORDER TO AVOID DUPE CONTENT
word_list = [sub_one_word_slugged, sub_two_word_slugged]
word_list_sorted = sorted(word_list)
page_slug = "{0}-and-{1}".format(word_list_sorted[0],word_list_sorted[1])
page_title = "{0} and {1}".format(word_list_sorted[0], word_list_sorted[1])
try:
obj = DifferncePage.objects.get(subject_one=word_list_sorted[0],subject_two=word_list_sorted[1])
redirect = "{0}{1}/".format(request.path, obj.slug)
return HttpResponseRedirect(redirect)
except DifferncePage.DoesNotExist:
# print 'This Comparison Does Not Exist. Create It'
try:
subject_one_subject=get_subject_one_data(word_list_sorted[0])['query']
subject_one_description = get_subject_one_data(word_list_sorted[0])['description']
subject_one_description_dictservice = ''.join(get_subject_one_data_dictservice(word_list_sorted[0])['data'])
except Exception:
errormsg1 = "<strong>Error occured (Subject One)</strong>: <ul><li>Tech glitch!</li></ul>"
# return{'form':form,'errormsg1':errormsg1}
return render_to_response('pages/compare.html',
{'form': form, 'errormsg1': errormsg1},
context_instance=RequestContext(request))
try:
subject_two_subject=get_subject_two_data(word_list_sorted[1])['query']
subject_two_description = get_subject_two_data(word_list_sorted[1])['description']
subject_two_description_dictservice =''.join(get_subject_two_data_dictservice(word_list_sorted[1])['data'])
except Exception:
errormsg2 = "<strong>Error occured (Subject Two)</strong>: <ul><li>Tech glitch!</li></ul>"
# return{'form':form,'errormsg2':errormsg2}
return render_to_response('pages/compare.html',
{'form': form, 'errormsg2':errormsg2},
context_instance=RequestContext(request))
subject_data_sources_api ='{0} {1}'.format(
''.join(get_subject_one_data_dictservice(word_list_sorted[0])['sources']),
''.join(get_subject_two_data_dictservice(word_list_sorted[1])['sources']),
)
obj = DifferncePage(title=page_title, subject_one=subject_one_subject, subject_two=subject_two_subject,
subject_one_data=subject_one_description,
subject_two_data=subject_two_description,
subject_one_data_dictservice=subject_one_description_dictservice,
subject_two_data_dictservice=subject_two_description_dictservice,
subject_data_sources=subject_data_sources_api)
obj.save()
redirect = "{0}{1}/".format(request.path, page_slug)
return HttpResponseRedirect(redirect)
return render_to_response('pages/compare.html',
{'form': form}, context_instance=RequestContext(request))
开发者ID:mmansour,项目名称:ghh,代码行数:66,代码来源:views.py
示例18: handle
def handle(self, *args, **options):
reader = csv.reader(open('{0}/docs/agents/CurrList_Comma_Delimited6.txt'.format(PROJECT_ROOT), 'r'), delimiter=',')
# reader = csv.reader(open('/home/mattym/webapps/vba/docs/CurrList_Comma_Delimited.txt', 'rU'), delimiter=',')
# reader = csv.reader(open(TEMPLATE_DIRS[0] + '/agents.csv', 'rU'), delimiter=',')
reader.next() # Skip first line
# col[1] lastname_primary or corp name
# col[2] firstname_secondary
# col[3] name_suffix
# col[4] lic_number
# col[5] lic_type
# col[6] lic_status
# col[7] lic_effective_date
# col[8] lic_expiration_date
# col[9] rel_lic_number (employing broker of agent etc...)
# col[10] empl_lastname_primary (agent's employer last name / Corp name)
# col[11] empl_firstname_secondary (agent's employer first name / Corp name)
# col[12] empl_name_suffix
# col[13] officerlastname
# col[14] officerfirstname
# col[15] officersuffixname
# col[16] rel_lic_type (employer type of license)
# col[17] address_1
# col[18] address_2
# col[19] city
# col[20] state
# col[21] zip_code
# col[22] foreign_nation
# col[23] foreign_postal_info
# col[24] county_code
# col[25] county_name
# col[26] restricted_flag
# col[27] misc_indicator
# col[28] ethics_and_agency_ind
from dateutil import parser
for col in reader:
dt_lic_effective_date = parser.parse(col[7])
dt_lic_expiration_date = parser.parse(col[8])
if col[5] != 'Salesperson':
clean_lic_type = col[5]
else:
clean_lic_type = "Agent"
the_title = '{0} {1} Real Estate {2} {3} {4}'.format(col[2],
col[1],
clean_lic_type,
col[19],
col[20]
)
full_name = "{0} {1} {2}".format(col[2], col[1], col[3])
full_name_officer = "{0} {1} {2}".format(col[14], col[13], col[15])
employer = "{0} {1}".format(col[10], col[11])
try:
agent = Agent.objects.get(license_id=col[4])
agent.in_sitemap = False
agent.licence_type = col[5]
agent.license_issue_date = dt_lic_effective_date
agent.license_exp_date = dt_lic_expiration_date
agent.employing_broker = col[9]
agent.licensed_officers = unicode(full_name_officer.strip()).encode("utf-8")
agent.save()
print 'Agent exists: {0}'.format(agent.title)
except Agent.DoesNotExist:
agent = Agent.objects.create(
title=unicode(the_title).encode("utf-8"),
slug=slugify(unicode(the_title).encode("utf-8")),
status=2,
full_name=unicode(full_name.strip()).encode("utf-8"),
first_name=unicode(col[2].strip()).encode("utf-8"),
last_name=unicode(col[1].strip()).encode("utf-8"),
mailing_address=unicode(col[17]).encode("utf-8"),
licensed_officers=unicode(full_name_officer.strip()).encode("utf-8"),
mailing_city=col[19],
mailing_state=col[20],
mailing_zip=col[21],
slugged_city=col[19],
slugged_state=col[20],
license_id=col[4],
license_type=col[5],
license_status=col[6],
license_issue_date=dt_lic_effective_date,
license_exp_date=dt_lic_expiration_date,
employing_broker=unicode(employer).encode("utf-8"),
in_sitemap=False,
# # affiliated_corporations= col[34],
# # licensed_officers = col[35]
# # main_office_address= col[30],
# # branches = col[32],
# # dba = col[33],
# # former_names = col[36],
#.........这里部分代码省略.........
开发者ID:mmansour,项目名称:VBA,代码行数:101,代码来源:import_cd.py
示例19: create_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)
开发者ID:skru,项目名称:cartridge_app,代码行数:75,代码来源:member_import.py
示例20: save
def save(self, *args, **kwargs): # pylint: disable=arguments-differ
if not self.slug:
self.slug = slugify(self.title)
super(NewsPost, self).save(*args, **kwargs)
开发者ID:geany,项目名称:www.geany.org,代码行数:4,代码来源:models.py
注:本文中的mezzanine.utils.urls.slugify函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论