本文整理汇总了Python中models.Group.save方法的典型用法代码示例。如果您正苦于以下问题:Python Group.save方法的具体用法?Python Group.save怎么用?Python Group.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Group
的用法示例。
在下文中一共展示了Group.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_parse_group
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def test_parse_group(self):
response = '''
{"response":[{"gid":1,"name":"ВКонтакте API","screen_name":"apiclub","is_closed":0,
"is_admin":1,"type":"group","photo":"http://cs400.vkontakte.ru/g00001/e_5ba03323.jpg",
"photo_medium":"http://cs400.vkontakte.ru/g00001/d_7bfe2183.jpg",
"photo_big":"http://cs400.vkontakte.ru/g00001/a_9a5cd502.jpg"},
{"gid":45,"name":"›››› ФМЛ 239 ››››","screen_name":"fml239","is_closed":1,"is_admin":0,"type":"group",
"photo":"http://cs39.vkontakte.ru/g00045/c_5a38eec.jpg",
"photo_medium":"http://cs39.vkontakte.ru/g00045/b_5a38eec.jpg",
"photo_big":"http://cs39.vkontakte.ru/g00045/a_5a38eec.jpg"}]}
'''
instance = Group()
instance.parse(json.loads(response)['response'][0])
instance.save()
self.assertEqual(instance.remote_id, 1)
self.assertEqual(instance.name, u'ВКонтакте API')
self.assertEqual(instance.screen_name, 'apiclub')
self.assertEqual(instance.is_closed, False)
self.assertEqual(instance.is_admin, True)
self.assertEqual(instance.type, 'group')
self.assertEqual(instance.photo, 'http://cs400.vkontakte.ru/g00001/e_5ba03323.jpg')
self.assertEqual(instance.photo_medium, 'http://cs400.vkontakte.ru/g00001/d_7bfe2183.jpg')
self.assertEqual(instance.photo_big, 'http://cs400.vkontakte.ru/g00001/a_9a5cd502.jpg')
示例2: addressbook_add_group
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def addressbook_add_group():
group_name = request.form.get('group_name', None)
data = {}
subst = {'group': group_name}
if not group_name:
dict_return(data, WARNING, u"Veuillez saisir un nom de groupe",
message_html=u"Veuillez saisir un nom de"
u"<strong> groupe</strong>.")
return json.dumps(data)
try:
group = Group(name=group_name)
group.save()
dict_return(data, SUCCESS,
u"%(group)s a été ajouté avec succès." % subst,
message_html=u"<strong>%(group)s</strong> "
u"a été ajouté avec succès." % subst)
except sqlite3.IntegrityError:
dict_return(data, INFO,
u"%(group)s existe déjà." % subst,
message_html=u"<strong>%(group)s</strong> existe déjà."
% subst)
except Exception as e:
subst.update({'err': e.message})
dict_return(data, ERROR,
u"Impossible d'enregistrer le groupe %(group)s : %(err)r" % subst,
message_html=u"Impossible d'enregistrer le groupe "
u"<strong>%(group)s</strong><br />"
u"<em>%(err)r</em>" % subst)
return json.dumps(data)
示例3: createGroup
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def createGroup(request):
'''
USAGE:
create a civi Group responsible for creating and managing civi content.
Please validate file uploads as valid images on the frontend.
File Uploads:
profile (optional)
cover (optional)
Text POST:
title
description
:returns: (200, ok, group_id) (500, error)
'''
pi = request.FILES.get('profile', False)
ci = request.FILES.get('cover', False)
title = request.POST.get(title, '')
data = {
"owner": Account.objects.get(user=request.user),
"title": title,
"description": request.POST.get('description',''),
"profile_image": writeImage('profile', pi, title),
"cover_image": writeImage('cover', ci, title)
}
try:
group = Group(**data)
group.save()
account.groups.add(group)
return JsonResponse({'result':group.id})
except Exception as e:
return HttpResponseServerError(reason=e)
示例4: group
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def group(name):
"""
New or existing group
"""
try:
group = Group.objects.get(name__exact=name)
except:
group = Group(name=name)
group.save()
return group
示例5: upload_opml_file
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def upload_opml_file(request):
if request.method == 'POST':
form = UploadOpmlFileForm(request.POST, request.FILES)
if form.is_valid():
#opml_file = request.FILES['file'].read()
#tree = ET.parse(opml_file)
#root = tree.getroot()
#for outline in root.iter('outline'):
# source = Source(user=request.user, xml_url=outline.get('xmlUrl'))
# source.save()
Source.objects.all().delete()
Group.objects.all().delete()
group = None
for event, elem in ET.iterparse(request.FILES['file']):
#import pdb; pdb.set_trace()
if elem.tag == 'body':
outlines = list(elem)
for outline in outlines:
if 'xmlUrl' not in outline.attrib:
group = Group(user=request.user, name=outline.attrib['title'])
group.save()
children = list(outline)
for child in children:
source = Source()
source.text = child.attrib['text']
source.title = child.attrib['title']
source.feed_type = child.attrib['type']
source.xml_url = child.attrib['xmlUrl']
source.html_url = child.attrib['htmlUrl']
source.save()
user_source = UserSource(user=request.user, source=source, group=group)
user_source.save()
elif 'xmlUrl' in outline.attrib:
print outline.attrib
source = Source()
source.text = outline.attrib['text']
source.title = outline.attrib['title']
source.feed_type = outline.attrib['type']
source.xml_url = outline.attrib['xmlUrl']
source.html_url = outline.attrib['htmlUrl']
source.save()
user_source = UserSource(user=request.user, source=source)
user_source.save()
return HttpResponseRedirect( reverse('entries') )
else:
form = UploadOpmlFileForm()
return render_to_response('feeds/upload_opml.html', {'form': form}, context_instance=RequestContext(request))
示例6: save_new_group
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def save_new_group(request):
if request.method == 'POST':
form = GroupForm(request.POST)
if form.is_valid():
group = Group()
group.name = form.cleaned_data['name']
group.max_loan_days = form.cleaned_data['max_loan_days']
group.save()
return HttpResponseRedirect('/webconf/couchauth/')
示例7: test_model_User_profile_change_default_group
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def test_model_User_profile_change_default_group(self):
username = "testusername"
user = DjangoUser(username=username)
user.save()
profile = user.profile
group = Group(name='testgroupname')
group.save()
profile.default_group = group
profile.save()
profile = User.objects.get(user=user)
self.assertEquals(profile.default_group, group)
示例8: creat_group
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def creat_group(request):
if request.method == "POST":
form = CreatGroupForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
introduction = form.cleaned_data['introduction']
grouptype = form.cleaned_data['grouptype']
group = Group(name=name, introduction=introduction, grouptype=grouptype, logo=STATIC_URL + 'img/face.png')
url_number = len(Group.objects) + 1
group.url_number = url_number
group.birthday = datetime.datetime.now()
if request.FILES:
path = 'img/group/' + str(url_number)
if not os.path.exists(MEDIA_ROOT + path):
os.makedirs(MEDIA_ROOT + path)
img = Image.open(request.FILES['logo'])
if img.mode == 'RGB':
filename = 'logo.jpg'
filename_thumbnail = 'thumbnail.jpg'
elif img.mode == 'P':
filename = 'logo.png'
filename_thumbnail = 'thumbnail.png'
filepath = '%s/%s' % (path, filename)
filepath_thumbnail = '%s/%s' % (path, filename_thumbnail)
# 获得图像的宽度和高度
width, height = img.size
# 计算宽高
ratio = 1.0 * height / width
# 计算新的高度
new_height = int(288 * ratio)
new_size = (288, new_height)
# 缩放图像
if new_height >= 288:
thumbnail_size = (0,0,288,288)
else:
thumbnail_size = (0,0,new_height,new_height)
out = img.resize(new_size, Image.ANTIALIAS)
thumbnail = out.crop(thumbnail_size)
thumbnail.save(MEDIA_ROOT + filepath_thumbnail)
group.thumbnail = MEDIA_URL + filepath_thumbnail
out.save(MEDIA_ROOT + filepath)
group.logo = MEDIA_URL + filepath
group.save()
sgcard = S_G_Card(user=request.user, group=group, is_active=True, is_admin=True,creat_time=datetime.datetime.now())
sgcard.save()
return HttpResponseRedirect('/group/' + str(url_number) + '/')
else:
form = CreatGroupForm()
return render_to_response('group/creat_group.html', {'form':form, 'STATIC_URL':STATIC_URL, 'current_user':request.user}, context_instance=RequestContext(request))
示例9: group
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def group(request, id):
c = {}
group_info = get_group(request.session['token'], id)
c['group_info'] = group_info
c['member_map'] = {member[u'user_id']: member[u'nickname'] for member in group_info[u'members']}
request.session['member_map'] = c['member_map']
if cache.get('group-%s' % id) and settings.CACHE_ENABLED:
c['group'] = cache.get('group-%s' % id)
return render(request, 'group.html', c)
if request.GET.get('ajaxLoad', '0') == '0' and settings.CACHE_ENABLED:
return render(request, 'group-loader.html', c)
get_attachment = lambda x: x[0].get('url', None) if len(x) else None
try:
group = Group.objects.get(id=id)
msgs = list(Message.objects.filter(group=group).order_by('created'))
if msgs:
after_id = msgs[-1].id
if not str(after_id).isdigit():
after_id = 0
elif str(after_id) != str(group_info[u'messages'][u'last_message_id']):
msgs += [Message(
id=msg[u'id'],
created=datetime.fromtimestamp(float(msg[u'created_at'])),
author=msg[u'user_id'] if msg[u'user_id'] != 'system' else 0,
text=msg[u'text'],
img=get_attachment(msg[u'attachments']),
likes=msg[u'favorited_by'],
n_likes=len(msg[u'favorited_by'])
) for msg in msg_concurrent(request.session['token'], id, after_id=after_id, n_workers=(int(group_info[u'messages'][u'count'])/10 + 1))]
group.analysis = analysis(request, msgs, group_info)
except Group.DoesNotExist:
msgs = [Message(
id=msg[u'id'],
created=datetime.fromtimestamp(float(msg[u'created_at'])),
author=msg[u'user_id'] if msg[u'user_id'] != 'system' else 0,
text=msg[u'text'],
img=get_attachment(msg[u'attachments']),
likes=msg[u'favorited_by'],
n_likes=len(msg[u'favorited_by'])
) for msg in msg_concurrent(request.session['token'], id, n_workers=(int(group_info[u'messages'][u'count'])/10 + 1))]
group = Group(id=id, analysis=analysis(request, msgs, group_info))
def save_msg(m):
m.group = group
m.save()
map(lambda m: save_msg(m), msgs)
if settings.CACHE_ENABLED:
cache.set('group-%s' % id, group, 180)
group.save()
c['group'] = group
return render(request, 'group.html', c)
示例10: groups
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def groups(request):
if request.method == "GET":
groups = Group.objects.all()
return HttpResponse(format_groups(groups), mimetype="application/json")
elif request.method == "POST":
group = Group()
data = json.loads(request.raw_post_data)
if len(data["name"]) > 0:
group.name = data["name"]
group.save()
return HttpResponse(format_groups([group]), mimetype="application/json")
raise "Got Error?"
示例11: dummy_groups
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def dummy_groups():
deepak = User.objects.get(pk=3)
susan = User.objects.get(pk=24)
james = User.objects.get(pk=25)
donna = User.objects.get(pk=29)
g = Group(id=1, name="friends", membership=3, creator_id=3)
g.save()
g1 = Group(creator=deepak, name="modi bhakts", membership=1)
g1.save()
g1.add_member(deepak)
g1.add_member(susan)
g1.add_member(james)
g1.add_member(donna)
g2 = Group(creator=deepak, name="times now", membership=2)
g2.save()
# g2.add_member(deepak)
g2.add_member(susan)
g2.add_channel_admin(deepak, deepak)
g2.add_channel_admin(donna, deepak)
g3 = Group(creator=deepak, name="core team", membership=3)
g3.save()
g3.add_member(deepak, deepak)
g3.add_member(susan, deepak)
g3.approve_member(susan)
g3.add_member(donna, deepak)
示例12: api_group_create
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def api_group_create(request):
api_result = {"api": "group_create", "status": "success"}
try:
token = request.POST["token"]
user = get_user_from_token(token)
name = request.POST["name"]
group_type = int(request.POST["group_type"])
if group_type == 1 or group_type == 2:
try:
existing_group = Group.objects.filter(name=name)
if len(existing_group) >= 1:
api_result["status"] = "failure"
api_result["error"] = "Group already exists"
else:
g = Group(creator=user, name=name, membership=group_type)
g.save()
if group_type == 2:
g.add_channel_admin(user, user)
elif group_type == 1:
g.add_member(user)
api_result["id"] = g.id
except Exception as e:
api_result["status"] = "failure"
api_result["error"] = e.message
elif group_type == 3:
try:
existing_group = Group.objects.filter(creator=user, name=name, membership=3)
if len(existing_group) >= 1:
api_result["status"] = "failure"
api_result["error"] = "Group already exists"
else:
g = Group(creator=user, name=name, membership=3)
g.save()
g.add_member(user, user)
g.approve_member(user)
api_result["id"] = g.id
except Exception as e:
api_result["status"] = "failure"
api_result["error"] = e.message
except Exception as e:
api_result["status"] = "failure"
api_result["error"] = e.message
pass
return JsonResponse(api_result)
示例13: test_model_Group_basic
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def test_model_Group_basic(self):
"""Test Group model"""
name = 'testgroup'
obj = Group(name=name)
obj.save()
self.assertIsNone(obj.parent)
self.assertIsNone(obj.details)
self.assertQuerysetEqual(obj.child_set.all(), [])
self.assertEqual(obj.get_absolute_url(), '/contacts/group/view/{}'.format(obj.id))
self.assertEqual(obj.get_root(), obj)
self.assertEqual(obj.get_tree_path(), [obj])
self.assertIsNone(obj.get_contact())
self.assertFalse(obj.has_contact())
self.assertEqual(obj.get_fullname(), name)
self.assertEqual(obj.get_perspective(), Perspective.objects.all()[0])
示例14: creat_group
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def creat_group(request):
if request.method == "POST":
form = CreatGroupForm(request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
introduction = form.cleaned_data["introduction"]
grouptype = form.cleaned_data["grouptype"]
group = Group(name=name, introduction=introduction, grouptype=grouptype, logo=STATIC_URL + "img/face.png")
url_number = len(Group.objects) + 1
group.url_number = url_number
group.birthday = datetime.datetime.now()
if request.FILES:
path = "img/group/" + str(url_number)
if not os.path.exists(MEDIA_ROOT + path):
os.makedirs(MEDIA_ROOT + path)
img = Image.open(request.FILES["logo"])
if img.mode == "RGB":
filename = "logo.jpg"
elif img.mode == "P":
filename = "logo.png"
filepath = "%s/%s" % (path, filename)
# 获得图像的宽度和高度
width, height = img.size
# 计算宽高
ratio = 1.0 * height / width
# 计算新的高度
new_height = int(260 * ratio)
new_size = (260, new_height)
# 缩放图像
out = img.resize(new_size, Image.ANTIALIAS)
out.save(MEDIA_ROOT + filepath)
group.logo = MEDIA_URL + filepath
group.save()
sgcard = S_G_Card(
user=request.user, group=group, is_active=True, is_admin=True, creat_time=datetime.datetime.now()
)
sgcard.save()
return HttpResponseRedirect("/group/" + str(url_number) + "/")
else:
form = CreatGroupForm()
return render_to_response(
"group/creat_group.html",
{"form": form, "STATIC_URL": STATIC_URL, "current_user": request.user},
context_instance=RequestContext(request),
)
示例15: addG
# 需要导入模块: from models import Group [as 别名]
# 或者: from models.Group import save [as 别名]
def addG(request):
if 'Permit' in request.GET and request.GET['Permit']:
permit_sudo = request.GET.get('Permit')
else:
permit_sudo = 0;
if 'repeated' in request.GET and request.GET['repeated']:
allow_repeated_GIDs = request.GET.get('repeated')
else:
allow_repeated_GIDs = 0;
# if 'groupName' in request.GET and request.GET['groupName']:
name = request.GET.get('groupName')
p1 = Group(groupname=name, permitSudo=permit_sudo, allowRepeatedGids=allow_repeated_GIDs)
p1.save()
groupList = Group.objects.all()
results = Commands.objects.all()
return render_to_response('home.html', locals())