def add_author(request): if request.method == 'POST': msg = request.POST['msg'] authorname = request.POST['author'] key = request.POST['key'] author = Author.objects.filter(name=authorname) if len(author) == 0: nr_authors = Author.objects.count() # This is our first author. He should be able to add users if nr_authors == 0: msg = json.loads(msg) msg['can_add_user'] = True msg['can_set_config'] = True else: return HttpResponseForbidden("Failed\r\n") else: author = author[0] if author.can_add_user: msg = decode_post(msg, author.decrypt_key, key) if not msg.has_key('can_set_config'): msg['can_set_config'] = False else: return HttpResponseForbidden("Failed\r\n") new_author = Author(name=msg['name'], decrypt_key=msg['decrypt_key'], \ email=msg['email'], about=msg['about'], \ can_add_user=msg['can_add_user'], \ can_set_config=msg['can_set_config']) new_author.save() return HttpResponse("Success\r\n") return HttpResponseForbidden("Not implemented\r\n")
def import_yaml(self, yaml_filename): with open(yaml_filename, 'r') as f: contents = yaml.load(f, Loader=yaml.FullLoader) Author.objects.all().delete() for author in contents: self.profiles_nb += 1 filename = author['bio'] if not os.path.isabs(filename): base_dir = os.path.abspath(os.path.dirname(yaml_filename)) filename = os.path.join(base_dir, filename) if not os.path.isfile(filename): raise CommandError(f'In file {yaml_filename}, ' f'file {filename} does not exist') header_img = None if 'header_img' in author: header_img = author['header_img'] db_author = Author(pseudo=author['pseudo'], name=author['name'], email=author['email'], bio=md_convert(filename)) if header_img is not None: db_author.header_img = header_img db_author.save()
def create_test_author(name="Authy McAuthface", email="*****@*****.**"): test_author = Author( name=name, email=email, bio="I write cool blogs", headshot_url= "http://getdrawings.com/img/female-headshot-silhouette-21.jpg") test_author.save() return test_author
def auth_add(request): if request.method == 'POST': form = AuthorForm(request.POST) if form.is_valid(): cd = form.cleaned_data email = cd['email'] name = cd['name'] website = cd['website'] author = Author(name=name, email=email, website=website) author.save() id = Author.objects.order_by('-id')[0].id return HttpResponseRedirect("/blog/admin/author_list/") else: form = AuthorForm() return render_to_response('admin_authadd.html',locals(), context_instance=RequestContext(request))
def main(): from blog.models import Author # Author.objects.all().delete() # AuthorList=[] # with open('author.txt') as f: # for line in f: # name ,email = line.split('#') # author=Author(name=name,email=email,qq='',addr='') # AuthorList.append(author) # # Author.objects.create(name=name,email=email,qq='',addr='') # # Author.objects.get_or_create(name=name,email=email,qq='',addr='') #比较慢 # f.close() # Author.objects.bulk_create(AuthorList) # Blog.objects.create()每保存一条就执行一次SQL,而bulk_create()是执行一条SQL存入多条数据, # 做会快很多!当然用列表解析代替 for 循环会更快!! AuthorList = [] f = open('author.txt') for line in f: parts = line.split('#') AuthorList.append(Author(name=parts[0], email=parts[1], qq='', addr='')) # Author.objects.create(name=name,email=email,qq='',addr='') # Author.objects.get_or_create(name=name,email=email,qq='',addr='') #比较慢 f.close() # 以上四行 也可以用 列表解析 写成下面这样 # BlogList = [Blog(title=line.split('****')[0], content=line.split('****')[1]) for line in f] Author.objects.bulk_create(AuthorList)
def handle(self, *args, **options): Blog.objects.all().delete() blog = Blog.objects.create(**BLOG_KWARGS) Author.objects.all().delete() Author.objects.bulk_create((Author(name=author) for author in AUTHOR_LIST)) Entry.objects.all().delete() Entry.objects.bulk_create((Entry(blog=blog, **entry) for entry in ENTRY_LIST))
def create_author(**kw): authors = Author.objects.all() if len(authors) == 0 or len(kw) != 0: return Author('Test', 'Test', '*****@*****.**', '1999-02-02', **kw) else: return authors[0]
def handle(self, *args, **options): len_insert = options['author'][0] if len_insert < 1: raise CommandError( f'argument = {len_insert} not in diapason: more then 1') else: ps = self.authors(len_insert) for p_in in ps: p = Author(username=p_in[0], first_name=p_in[1], last_name=p_in[2], mail=p_in[3]) p.save(force_insert=True) self.stdout.write(self.style.SUCCESS(f'author: {p} ')) self.stdout.write( self.style.SUCCESS(f'Success insert {len_insert} Author'))
def author(request): author = get_object_or_404(Author, pk=1) context = { 'author': author, 'author_last_name': Author().last_name, 'blog_title': Blog().blog_title } print(context) return render(request, 'blog/index.html', context)
def handle(self, *args, **options): """Clear old instances and create new ones.""" Blog.objects.all().delete() blog = Blog.objects.create(**BLOG_KWARGS) Author.objects.all().delete() Author.objects.bulk_create( Author(name=author) for author in AUTHOR_LIST) Entry.objects.all().delete() Entry.objects.bulk_create( Entry(blog=blog, **entry) for entry in ENTRY_LIST)
def init_author(): """ name = models.CharField(max_length=90) qq = models.CharField(max_length=30) addr = models.TextField() email = models.EmailField() """ for author_name in author_name_list: qq = "" for i in range(10): # print(random.randrange(9)) # 随机生成9位数的QQ qq = qq + str(random.randrange(9)) i = random.randrange(4) author = Author(name=author_name, addr=author_address_list[i], email=qq + "@qq.com", qq=qq) author.save()
def handle(self, *args, **options): Blog.objects.all().delete() blog = Blog.objects.create( name='Recettes', lang='french', tagline='Des recettes dans toutes les langues!') Author.objects.all().delete() Author.objects.bulk_create( (Author(name=author) for author in AUTHOR_LIST)) Entry.objects.all().delete() Entry.objects.bulk_create( (Entry(blog=blog, **entry) for entry in ENTRY_LIST))
def setUp(self): """Prepare initial data for testing.""" self.author = Author(name="Dante Alighieri") self.blog = Blog( lang="italian", name="Divina Commedia", tagline= "The Divine Comedy is a Italian narrative poem by Dante Alighieri.", ) self.entry = Entry( blog=self.blog, headline="Inferno - Canto primo", body_text=("Nel mezzo del cammin di nostra vita " "mi ritrovai per una selva oscura, " "ché la diritta via era smarrita."), )
def register(request): if request.method == 'POST': f = CustomUserCreationForm(request.POST) if f.is_valid(): # send email verification activation_key = helpers.generation_activation_key( username=request.POST['username']) subject = "App Verification" message = '''\n Please click to verify your account \n\n{0}://{1}/cadmin/activate/account/?key={2}'''.format( request.scheme, request.get_host(), activation_key) error = False try: send_mail(subject, message, settings.SERVER_EMAIL, [request.POST['email']]) messages.add_message( request, messages.INFO, 'Account created! Click on the link sent to your email to activate your account.' ) except: error = True messages.add_message( request, messages.INFO, 'Unable to send email verification. Please try again later.' ) if not error: u = User.objects.create_user(request.POST['username'], request.POST['email'], request.POST['password1'], is_active=0, is_staff=True) author = Author() author.activation_key = activation_key author.user = u author.save() return redirect('register') # f.save() # messages.success(request, 'Account created suvvessfully') # return redirect('register') else: f = CustomUserCreationForm() return render(request, 'cadmin/register.html', {'form': f})
def register(request): if request.method == 'POST': f = CustomUserCreationForm(request.POST) if f.is_valid(): # Send email verifications activation_key = generate_activation_key( username=request.POST['username']) subject = 'TheGreatDjangoBlog Account Verification' message = '''\n Please visit the following link to verify your account\n\n {0}://{1}/cadmin/activate/account/?key={2} '''.format(request.scheme, request.get_host(), activation_key) print(request.POST['email']) error = False try: send_mail(subject, message, settings.SERVER_EMAIL, [request.POST['email']]) messages.add_message( request, messages.INFO, 'Account created! Click on the link sent to your email to activate the account' ) except: error = True messages.add_message( request, messages.INFO, 'Unable to send email verification. Please try again') if not error: u = User.objects.create_user( username=request.POST['username'], email=request.POST['email'], password=request.POST['password1'], is_active=0, is_staff=True, ) author = Author() author.user = u author.activation_key = activation_key author.save() return redirect('register') else: f = CustomUserCreationForm() return render(request, 'cadmin/register.html', {'form': f})
def register(request): if request.method == "POST": f = CustomUserCreationForm(request.POST) if f.is_valid(): # Send Email verification. Generate activationKey by importing from helpers.py # Check 'helpers.py' for the code. activation_key = helpers.generate_activation_key( username=request.POST['username']) subject = "The Django Blog Account Verification" message = '''Hello {0},\n You have created an account in our site. \nPlease visit the following link to verify the account \n\n{1}://{2}/cadmin/activate/account/?key={3} \n\n If you did not create any account with us, please ignore this message.'''.format( request.POST['username'], request.scheme, request.get_host(), activation_key) error = False # Try to send Email. If any errors, show unable to send email error. try: send_mail(subject, message, settings.SERVER_EMAIL, [request.POST['email']]) messages.add_message( request, messages.INFO, "Account created! Click on the link sent to your email to activate the account." ) except: error = True messages.add_message( request, messages.INFO, "Unable to send email verification. Please try again.") if not error: # If there are no errors, take all the data and store it in variable. u = User.objects.create_user(request.POST['username'], request.POST['email'], request.POST['password1'], is_active=0) # Now Save the user data into Author() model. author = Author() author.activation_key = activation_key author.user = u author.save() return redirect('register') else: f = CustomUserCreationForm() return render(request, 'cadmin/register.html', { 'form': f, })
def signup_view(request): if request.method == 'POST': try: # reading inputs first_name = request.POST["fullname"] username = request.POST["username"] email = request.POST["email"] password = request.POST["password"] # checking for empty fields assert first_name != '' and username != '' and email != '' and password != '' # creating new user object user = User.objects.create_user(username=username, email=email, password=password, first_name=first_name) user.save() Author(user=user).save() return HttpResponseRedirect(reverse('index')) except: return render(request, 'blog/signup.html', {'message': 'fill all the details'}) return render(request, 'blog/signup.html')
def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): # send email verification now activation_key = helpers.generate_activation_key( username=request.POST['username']) subject = 'The Django Blog Account Activation' message = f'''\n please click on the link below to activate your account: \n {request.scheme}://{request.get_host()}/cadmin/activate/account/?key={activation_key} ''' error = False try: send_mail(subject, message, settings.SERVER_EMAIL, [request.POST['email']]) messages.success( request, f'Account created! Click on the link sent to your email to activate the account' ) except: error = True messages.success(request, 'Unable to send email. Please try again') if not error: u = User.objects.create_user(request.POST['username'], request.POST['email'], request.POST['password1'], is_active=0) author = Author() author.activation_key = activation_key author.user = u author.save() return redirect('login') else: form = UserRegisterForm() return render(request, 'cadmin/register.html', {'form': form})
def _import_author(self, author_data): author = Author(username=author_data['username'], email=author_data['email'], bio=author_data['bio']) return author
def author_create(request): name = request.POST.get('name', '') author = Author(name=name) author.save() authors = Author.objects.order_by('id') return render_to_response('authors/index.html', {'authors': authors}, context_instance=RequestContext(request))