def post(self, request): form = self.form_class(request.POST or None) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user_email = form.cleaned_data['email'] user.set_password(password) user.save() profile = Profile(user=user) profile.save() user = authenticate(username=username, password=password) send_mail('Social School - Email Activation', 'Link to email activation', '*****@*****.**', [user_email]) if user is not None: if user.is_active: login(request, user) return redirect('index') else: return render(request, self.template_name, {'form': form})
def signup_user(request): if request.method == 'GET': context = { 'form': RegisterForm(), } return render(request, 'accounts/signup.html', context) else: # &qy^a}ay4J\vpXeR form = RegisterForm(request.POST) if form.is_valid(): user = form.save() profile = Profile( user=user, phone=request.POST['phone'] ) profile.save() login(request, user) return redirect('index') else: context = { 'form': form, } return render(request, 'accounts/signup.html', context)
def user_created(sender, instance, created, *args, **kwargs): if created: profile = Profile( user=instance, userPhotoURL= "image/upload/v1607681887/events/user-photos/user-default.jpg") profile.save()
def register_view(request): if request.method == "POST": email = request.POST['email'] username = request.POST['username'] password = request.POST['password'] password_confirm = request.POST['password_confirm'] if password != password_confirm: messages.error(request, "password is not a match") return render(request, "accounts/register.html") try: pass user = User.objects.create_user(username, email, password) profile = Profile(user=user) profile.save() except IntegrityError: messages.error(request, "Username is taken already") return render(request, 'accounts/register.html') login(request, user) messages.success(request, f'Account created for {username}!') return redirect("accounts:user_login") else: # messages.error(request, "Unsuccessful registration. Invalid information.") form = UserCreationForm() return render(request, "accounts/register.html", {"form": form})
def mypage(request): message='get method' if request.method == "POST": test='post' mypageform=MypageForm(request.POST) if mypageform.is_valid(): profile = Profile.objects.get(user=request.user) profile.city = mypageform.cleaned_data['city'] profile.address = mypageform.cleaned_data['address'] profile.phone = mypageform.cleaned_data['phone'] profile.save() user=request.user user.first_name = mypageform.cleaned_data['first_name'] user.save() message = 'updated' else: message = mypageform.errors user=User.objects.get(id=request.user.id) #프로필 있는지 확인 없으면생성 try: profile=Profile.objects.get(user=request.user) except: new_profile=Profile(user=request.user) new_profile.save() mypageform = MypageForm({'first_name':request.user.first_name ,'city':user.profile.city,'address':user.profile.address, 'phone':user.profile.phone}) context={'message':message,'point':user.profile.point, 'mypageform':mypageform} return render(request,"accounts/mypage.html", context)
def me(self, request): """ Get personal account details, if logged in. """ if request.user.is_authenticated(): try: profile = request.user.profile except Profile.DoesNotExist: p = Profile(user=request.user) p.save() serializer = UserSerializer(instance=request.user, context={'request': request}) if request.method == 'PATCH': password = request.data.pop('password', None) serializer.update(request.user, request.data) if password: request.user.set_password(password) request.user.save() return Response(serializer.data) else: return Response({'authenticated': False})
def custom_complete(request, backend, u_hash, u_hash_sess, *args, **kwargs): """Authentication complete view""" if u_hash and u_hash == u_hash_sess: # if invited tester join course - create user immediately without confirmation email. data = request.POST.dict().copy() user = request.backend.strategy.create_user(**data) user.backend = 'django.contrib.auth.backends.ModelBackend' user = authenticate(username=user.username, password=data.get('password')) login(request, user) request.session['u_hash'] = u_hash response = do_complete( request.backend, _do_login, request.user, redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) if not u_hash or u_hash != u_hash_sess: # if not invited tester join course - logout user logout(request) # add resend_user_email to the session to be able to resend link request.session['resend_user_email'] = request.POST.get('email') # getting just created CustomCode cc = CustomCode.objects.filter(email=request.POST.get('email')).order_by('-id').first() if cc: request.session['cc_id'] = cc.id # remove u_hash from session request.session.pop('u_hash', None) if request.user.is_authenticated(): Profile.check_tz(request) return response
def sign_up(request): if request.method == 'POST': form = Register(request.POST) if form.is_valid(): email = form.cleaned_data['email'] get_email = User.objects.filter(email=email) for i in get_email: if i.email == email: messages.warning(request, 'Email already exists.') context = {'form': form} return render(request, 'register.html', context) break user = form.save() user_profile = Profile(user=user) user_profile.save() messages.success(request, 'Account Created Successfully.') return redirect('login') else: context = { 'form': form, } return render(request, 'register.html', context) else: form = Register() context = { 'form': form, } return render(request, 'register.html', context)
def setUp(self): self.credentials = { "email": "*****@*****.**", "password": "******" } self.user = User.objects.create_user( email=self.credentials['email'], password=self.credentials['password'], first_name="oliver", last_name="twist", role=1) # THIS SHOULD BE CHANGED IF WE ARE USING CONFIRMATION EMAIL FOR USERS self.email_confirmed, _ = EmailConfirmed.objects.get_or_create( user=self.user) self.email_confirmed.confirmed = True self.email_confirmed.save() self.token = Token.objects.get(user=self.user) self.profile = Profile(user=self.user, instaAccount="insta") self.profile.save() self.event = Event(eventOwner=self.user, eventType="A", title="title to watch", status="O") self.event.save()
def save(self): username = self.cleaned_data["username"] email = self.cleaned_data["email2"] password = self.cleaned_data["password2"] first_name = self.cleaned_data.get("first_name", "") last_name = self.cleaned_data.get("last_name", "") newsletter = self.cleaned_data.get("newsletter", False) accepted_tos = self.cleaned_data.get("accepted_tos", False) user = User(username=username, first_name=first_name, last_name=last_name, email=email, password=password, is_staff=False, is_active=False, is_superuser=False) user.set_password(password) user.save() profile = Profile(user=user, wants_newsletter=newsletter, accepted_tos=accepted_tos) profile.save() return user
def save(self, commit=True): self.instance.is_active = False result = super().save(commit) profile = Profile(user=result) if commit: profile.save() return result
def create(self, validated_data): email = validated_data["email"] username = validated_data["username"] first_name = validated_data["first_name"] last_name = validated_data["last_name"] password = validated_data["password"] profile_data = validated_data.pop("profile") if (not validate_contact_no(None, profile_data["contact_no"])): raise serializers.ValidationError( "account with this contact no. exists") user_profile = Profile(**profile_data) #user is created and saved user = User.objects.create_user(profile=user_profile, email=email, username=username, first_name=first_name, last_name=last_name, password=password) #after user is created and saved,profile is also saved in database user_profile.save() return user
def registration(request): if request.user.is_authenticated: return redirect(reverse('dashboard')) if request.method == 'POST': registration_form = UserRegistrationForm(request.POST) if registration_form.is_valid(): registration_form.save() username = request.POST['username'] password = request.POST['password1'] user = User.objects.get(username=username) profile = Profile(user=user, first_name=request.POST['first_name'], surname=request.POST['last_name'], email=request.POST['email'], username=request.POST['username']) profile.save() user = auth.authenticate(username=username, password=password) if user: auth.login(user=user, request=request) messages.success(request, 'You have successfully registered') return redirect(reverse('dashboard')) else: messages.error(request, 'Unable to register your account at this time') else: registration_form = UserRegistrationForm() return render(request, 'registration.html', {'registration_form': registration_form})
def save_user(self, request, sociallogin, form=None): user = super().save_user(request, sociallogin, form) p = Profile(user=user) p.save() return user
def signup(request): regist_terms=Texts.objects.get(name="regist_terms") privacy_info_terms=Texts.objects.get(name="privacy_info_terms") if request.method=="POST": userform = SignupForm(request.POST) if userform.is_valid(): user = userform.save(commit=False) user.username = userform.cleaned_data['username'] user.save() profile = Profile(user=user) profile.save() return HttpResponseRedirect(reverse("signup_ok")) return render(request, "accounts/signup.html", { 'userform': userform, 'message':'입력정보를 정확히 확인해주세요.', 'regist_terms':regist_terms.contents, 'privacy_info_terms':privacy_info_terms.contents, }) elif request.method=="GET": userform = SignupForm() return render(request, "accounts/signup.html", { 'userform':userform, 'message':'첫 화면', 'regist_terms':regist_terms.contents, 'privacy_info_terms':privacy_info_terms.contents, })
def mypage(request): message='get method' if request.method == "POST": test='post' mypageform=MypageForm(request.POST, request.FILES) if mypageform.is_valid(): profile = Profile.objects.get(user=request.user) profile.userid = mypageform.cleaned_data['userid'] profile.skill = mypageform.cleaned_data['skill'] profile.context = mypageform.cleaned_data['context'] profile.server = mypageform.cleaned_data['server'] profile.race = mypageform.cleaned_data['race'] profile.image = mypageform.cleaned_data['image'] profile.save() user=request.user user.save() messages.success(request, '마이페이지가 작성됐습니다. 유저 목록을 확인해주세요.') else: message = mypageform.errors user=User.objects.get(id=request.user.id) #프로필 있는지 확인 없으면생성 try: profile=Profile.objects.get(user=request.user) except: new_profile=Profile(user=request.user) new_profile.save() mypageform = MypageForm({'userid':user.profile.userid,'skill':user.profile.skill, 'context':user.profile.context,'server':user.profile.server, 'race':user.profile.race,'image':user.profile.image}) return render(request,"accounts/mypage.html", { 'message':message, 'mypageform':mypageform })
def register_view(request): form = RegisterForm.UserRegisterForm(request.POST or None) if request.method == 'POST': if form.is_valid(): user = form.save(commit=False) user.save() #Authenticates user before logging in # new_user = authenticate(username=user.username, password=password) # login(request, new_user) #Set default values to accounts_profile new_entry = Profile(email=user, ethaddress='null', indicativecontribution=0, actualcontribution=0, mytoken=0, bonustoken=0, tokenwithdrawn=0) new_entry.save() print('Successfully registered') return redirect('../') context = { "form": form, } return render(request, "register.html", context)
def _create_anonymous_user(request): def _create_username(): _username = '******'.format(User.objects.last().pk + 1) exists = len(User.objects.filter(username=_username)) while exists == 1: _username += get_random_string(length=5) exists = len(User.objects.filter(username=_username)) return _username username = _create_username() user_data = {} profile_data = {} user_data['username'] = username profile_data.update({'disabled': True, 'anonymous_login': True}) user = User(**user_data) user.save() profile_data['user'] = user profile = Profile(**profile_data) profile.save() next_uri = reverse('accounts.change_password') key = create_user_key(user, usage_left=None, next=next_uri) user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return key
def setUp(self): self.topic = Topic(name="Development") self.topic.save() self.tag = Tag(name="Press Release") self.tag.save() self.user = User(username="******", email="*****@*****.**", password="******") self.user.save() self.author = Profile(user=self.user, job="Tech-lead", bio="web dev from sudan") self.author.save() self.article = Article(main_title="Making Python", author=self.author, topic=self.topic, content="Hello World") self.article.save() self.article.tags.add(self.tag) self.author.save() self.comment = Comment(article=self.article, text="What is python any way") self.comment.save() self.reply = Reply(comment=self.comment, text="a programming language") self.reply.save()
def views_register(request): if request.method == "POST": first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] city = request.POST['city'] country = request.POST['country'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] if password != confirm_password: messages.error(request, "password in not match") return render(request, "accounts/register.html") try: pass user = User.objects.create_user(username, email, password, first_name=first_name, last_name=last_name) profile = Profile(city=city, country=country, user=user) profile.save() except IntegrityError: messages.error(request, "Username is taken already") return render(request, 'accounts/register.html') login(request, user) return redirect("events:musics_index") else: form = UserCreationForm() return render(request, "accounts/register.html", {"form": form}) return render(request, "accounts/register.html")
def update_profile(request): if request.method == "POST": user = User.objects.get(id=request.user.id) try: profile_user = Profile.objects.get(user=request.user) except: profile_user = Profile() bio = request.POST['edit_bio'] interest = request.POST['edit_interests'] email = request.POST['edit_email'] github = request.POST['edit_github'] linkedin = request.POST['edit_linkedin'] if 'picture' in request.FILES: if request.FILES['picture']: profile_picture = request.FILES['picture'] profile_user.picture = profile_picture else: pass profile_user.bio = bio if len(bio) > 140: messages.error(request, 'Your bio cant contain more than 140 characters') return redirect('dashboard') profile_user.interests = interest profile_user.github = github profile_user.linkedIn = linkedin user.email = email user.save() profile_user.user = user profile_user.save() return redirect('dashboard')
def mypage(request): message=None if request.method == "POST": mypageform=MypageForm(request.POST) if mypageform.is_valid(): profile = Profile.objects.get(user=request.user) profile.phone = mypageform.cleaned_data['phone'] profile.postcode=request.POST.get('postcode') profile.address=request.POST.get('address') profile.address_detail=request.POST.get('address_detail') check = request.POST.get('ads_agree') if check == None : profile.ads_agree=False else: profile.ads_agree=True profile.save() user=request.user user.first_name = mypageform.cleaned_data['first_name'] user.save() message = '정보가 업데이트 되었습니다.' else: message = mypageform.errors user=User.objects.get(id=request.user.id) #프로필 있는지 확인 없으면생성 try: profile=Profile.objects.get(user=request.user) except: new_profile=Profile(user=request.user) new_profile.save() mypageform = MypageForm({'first_name':request.user.first_name, 'phone':user.profile.phone}) context={'message':message,'mypageform':mypageform, 'user':user, 'brands':get_brands(),} return render(request,"accounts/mypage.html", context)
def setUp(self): super(ProfileAttributeTestCase, self).setUp() with requests_mock.mock() as m: self._mock_cards_reserve(m) self.user = User(username="******") self.user.save() self.profile = Profile(user=self.user) self.profile.save()
def save(self, commit=True): self.instance.is_active = False result = super().save(commit) biography = self.cleaned_data['biography'] profile = Profile(biography=biography, user=result) if commit: profile.save() return result
def form_valid(self, form): try: self.request.user.profile.title = form.cleaned_data['title'] self.request.user.profile.save() except: profile = Profile(user=self.request.user, title=form.cleaned_data['title']) profile.save() return super(ProfileView, self).form_valid(form)
def test_date_of_birth_userprofile(self): user = User.objects.get(pk=1) date_of_birth = datetime.date.today() # profile = user.profile # profile.date_of_birth = date_of_birth profile = Profile(user=user, date_of_birth=date_of_birth) profile.save() self.assertEquals(profile.date_of_birth, datetime.date.today())
def save(self, user_name): user = get_object_or_404(User, username=user_name) user.is_staff = True user.save() userProfile = Profile( user=user, role='Teacher', ) userProfile.save()
def create(self,validated_data): user = User.objects.create_user(**validated_data) profile = Profile() assign_role(user,'customer') grant_permission(user,CREATE_RIDE) grant_permission(user,VIEW_RIDE_HISTORY) profile.user = user profile.save() return user
def save(self, commit=True): # self.instance.is_active = False result = super().save(commit) phone = self.cleaned_data['phone'] country = self.cleaned_data['country'] profile = Profile(phone=phone, country=country, user=result) if commit: profile.save() return result
def form_valid(self, form): """ If the form is valid, redirect to the supplied URL. """ user = self.request.user try: p = user.profile except ObjectDoesNotExist: p = Profile(user=user) p.save() p.full_name = form.cleaned_data['full_name'] p.phone = form.cleaned_data['phone'] p.address = form.cleaned_data['address'] p.save() o = Order(user=user, session_key=self.request.session.session_key, shipping=form.cleaned_data['shipping']) o.save() self.success_url = reverse('orders:ThanksForOrder', kwargs={'pk': o.id}) return super(CreateOrderView, self).form_valid(form)
def setUp(self): user_obj = User(username='******', email='*****@*****.**', first_name='Alice') user_obj.set_password("somerandopassword") user_obj.save() data = {'rank': 'astronaut'} profile = Profile(user=user_obj, **data) profile.save()
def profile(request): # if not request.POST.get('number'): profiles = Profile(user=request.user, first_name=request.POST.get('fname', False), last_name=request.POST.get('lname', False), email=request.POST.get('email', False), number=request.POST.get('number', False), gender=request.POST.get('gender', False)) if not profiles.first_name and not profiles.gender: return render(request, 'accounts/profile.html', {}) else: profiles.save() return render(request, 'accounts/showprofile.html', {})
def user(request, username): users = Profile.objects.all().order_by('-score') #The user that is being viewed try: user = User.objects.get(username=username) except: user = None #if the user being viewed is the same as the on logged on then give him permission to edit if user==request.user: editable = True else: editable = False if user: #create profile if none try: profile = user.get_profile() except ObjectDoesNotExist: profile = Profile(user=user) profile.save() usercomments = Comment.objects.filter(user=user).order_by('content_type') userchapters = Chapter.objects.filter(author=user, visible=True) userrevisions = Revision.objects.filter(revision_user=user).exclude(counter=1) userratings = Vote.objects.filter(user=user) if (usercomments or userchapters or userrevisions or userratings): activity=True else: activity = False return render_to_response('accounts/user.html', {'editable': editable, 'profile': user, 'users':users, 'username':username, 'usercomments':usercomments, 'userchapters':userchapters, 'userrevisions':userrevisions, 'userratings':userratings, 'activity':activity, }, context_instance = RequestContext(request) ) else: activity = False return render_to_response('accounts/user.html', {'editable': editable, 'profile': user, 'users':users, 'username':username, 'activity':activity, }, context_instance = RequestContext(request) )
def save(self): username = self.cleaned_data["username"] email = self.cleaned_data["email2"] password = self.cleaned_data["password2"] first_name = self.cleaned_data.get("first_name", "") last_name = self.cleaned_data.get("last_name", "") newsletter = self.cleaned_data.get("newsletter", False) user = User(username=username, first_name=first_name, last_name=last_name, email=email, password=password,is_staff=False, is_active=False, is_superuser=False) user.set_password(password) user.save() profile = Profile(user=user, wants_newsletter=newsletter) profile.save() return user
def signlogup(request): data = get_global_data(request) data['message'] = False if request.user.is_authenticated(): return HttpResponseRedirect('/profile/') elif request.method == 'POST': form = LoginForm(request.POST) if form.is_valid() and 'password' in request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: request.session.set_expiry(60*60*24*365) login(request, user) return HttpResponseRedirect('/profile/') else: data['message'] = 'Эккаунт заблокирован' else: data['message'] = 'Неправильная пара логин/пароль' elif 'username' in request.POST: username = request.POST['username'] try: user = User.objects.create_user(username, username, username) user.is_active = False user.is_staff = False activate_code = md5.new(username).hexdigest() send_html_mail('Activation letter', username, {'name': username, 'code': activate_code}, 'emails/activate_letter.html', sender='*****@*****.**') user.save() profile = Profile(user = user, phone = '+7 ') profile.save() return { 'message': 'Спасибо за регистрацию. Вам выслано письмо с инструкциями по активации эккаунта.' } except: if User.objects.get(username=username) is not None: data['message'] = 'Пользователь с таким e-mail уже зарегистрирован' else: data['message'] = 'Неизвестная ошибка при добавлении пользователя. Обратитесь в поддержку' else: form = LoginForm() data['login_form'] = form return data
def complete(request, *args, **kwargs): data_to_use = request.POST or request.GET form = SignUpForm(data_to_use) post_data = request.POST.copy() post_data.pop('csrfmiddlewaretoken', None) # if there's only email and csrf field in POST - it's login by email. if len(post_data.keys()) == 1 and 'email' in post_data: login_by_email = True form = CompleteEmailForm(request.POST) if form.is_valid(): post_data.update({ 'first_name': '', 'last_name': '', 'institution': '', }) request.POST = post_data else: login_by_email = False if form.is_valid() or 'verification_code' in request.GET: try: resp = social_complete(request, 'email', *args, **kwargs) if not ('confirm' in request.POST or login_by_email) and request.user.is_authenticated(): Profile.check_tz(request) return resp except AuthMissingParameter: messages.error(request, 'Email already verified.') if request.user.is_authenticated(): Profile.check_tz(request) return redirect('ctms:my_courses') else: # add message with transformed form errors err_msg = "\n".join([ "{} - {}".format( k.capitalize(), ", ".join(i.lower() for i in v) ) for k, v in form.errors.items() ]) messages.error( request, "You passed not correct data. {}".format(err_msg) ) # if form is not valid redirect user to page where he came from return redirect(reverse("login"))
def edit_profile(request): try: profile = request.user.get_profile() except ObjectDoesNotExist: profile = Profile(user=request.user) profile.save() user = request.user users = Profile.objects.all().order_by('-score') if request.method == 'POST': form = ProfileUserForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save() return HttpResponseRedirect('/users/'+request.user.username+'/') else: form = ProfileUserForm(request.POST, request.FILES, instance=profile) else: form = ProfileUserForm(instance=profile) return render_to_response('accounts/user_edit.html', {'form': form,'users':users,'user':user},context_instance = RequestContext(request))
def fixture(): from django.contrib.auth.models import Group from accounts_web.settings import CONFIG group_default = Group(name=CONFIG['DEFAULT_GROUP']) group_default.save() from django.contrib.auth.models import User from accounts.models import Profile for user in User.objects.all(): profile = Profile(user=user, group=group_default) profile.save() from firewall.models import RuleKit from firewall.patterns import ACTION_ALLOW rule_kit = RuleKit(group=group_default, default_action=ACTION_ALLOW) rule_kit.save() from firewall.models import NetInterface from firewall.patterns import INTERNAL_IF default_if = NetInterface(if_name='eth0', if_type=INTERNAL_IF) default_if.save()
def user_commented(sender, **kwargs): request = kwargs.get("request") comment = kwargs.get("comment") try: p = request.user.get_profile() except ObjectDoesNotExist: p = Profile(user=request.user) p.save() contentpk = comment.object_pk contenttype = comment.content_type # Email author when comment posted on authors chapter (comment on chapter) try: chapter_author = comment.content_object.author except: chapter_author = comment.content_object.created_by try: author_contact = Contact.objects.get(email=chapter_author.email) except: author_contact = None if not chapter_author == comment.user and author_contact: hyperlink = "http://%s%s#c%s" % ( Site.objects.get_current(), comment.content_object.get_absolute_url(), comment.id, ) content_mail = '%s with %s points has commented your chapter: [%s](%s), saying: "%s"' % ( comment.user, comment.user.get_profile().score, comment.content_object.title, hyperlink, truncate_words(comment.comment, 8), ) organizer_message = UserMessage( contact=author_contact, user=chapter_author, content_mail=content_mail, creation_date=datetime.now(), category=3, hyperlink=hyperlink, actor=comment.user, ) if isinstance(comment.content_object, Chapter): organizer_message.chapter = comment.content_object if isinstance(comment.content_object, Article): organizer_message.chapter = comment.content_object.chapter_related organizer_message.save() hyperlink_usermessage = "http://%s%s?usermessage=%s#c%s" % ( Site.objects.get_current(), comment.content_object.get_absolute_url(), organizer_message.id, comment.id, ) content = '%s with %s points has commented your chapter: [%s](%s), saying: "%s"' % ( comment.user, comment.user.get_profile().score, comment.content_object.title, hyperlink_usermessage, truncate_words(comment.comment, 8), ) organizer_message.hyperlink_usermessage = hyperlink_usermessage organizer_message.content = content organizer_message.save() # email instantly plaintext = get_template("email/comment_on_chapter.txt") html = get_template("email/comment_on_chapter.html") c = Context({"organizer_message": organizer_message}) email_plaintext = plaintext.render(c) email_html = html.render(c) msg = EmailMultiAlternatives( "Winning Without Losing: comment on your chapter", email_plaintext, "*****@*****.**", [organizer_message.contact.email], ) msg.attach_alternative(email_html, "text/html") msg.send() # Email send when someone has commented in a thread where another user has commented (comment on comment) users = User.objects.all() for user in users: try: contact = Contact.objects.get(email=user.email) except: contact = None if contact: try: usercomment = Comment.objects.get(content_type=contenttype, object_pk=contentpk, user=user) except MultipleObjectsReturned: usercomment = Comment.objects.filter(content_type=contenttype, object_pk=contentpk, user=user)[0] except ObjectDoesNotExist: usercomment = None if usercomment and user != comment.user: hyperlink = "http://%s%s#c%s" % ( Site.objects.get_current(), comment.content_object.get_absolute_url(), comment.id, ) content_mail = '%s with %s points has commented the same chapter as you: [%s](%s), saying: "%s"' % ( comment.user, comment.user.get_profile().score, comment.content_object.title, hyperlink, truncate_words(comment.comment, 8), ) organizer_message = UserMessage( contact=contact, user=user, content_mail=content_mail, creation_date=datetime.now(), category=1, hyperlink=hyperlink, actor=comment.user, ) if isinstance(comment.content_object, Chapter): organizer_message.chapter = comment.content_object if isinstance(comment.content_object, Article): organizer_message.chapter = comment.content_object.chapter_related organizer_message.save() hyperlink_usermessage = "http://%s%s?usermessage=%s#c%s" % ( Site.objects.get_current(), comment.content_object.get_absolute_url(), organizer_message.id, comment.id, ) content = '%s with %s points has commented the same chapter as you: [%s](%s), saying: "%s"' % ( comment.user, comment.user.get_profile().score, comment.content_object.title, hyperlink_usermessage, truncate_words(comment.comment, 8), ) organizer_message.hyperlink_usermessage = hyperlink_usermessage organizer_message.content = content organizer_message.save() # email instantly plaintext = get_template("email/comment_on_comment.txt") html = get_template("email/comment_on_comment.html") c = Context({"organizer_message": organizer_message}) email_plaintext = plaintext.render(c) email_html = html.render(c) msg = EmailMultiAlternatives( "Winning Without Losing: Someone has commented the same chapter as you", email_plaintext, "*****@*****.**", [organizer_message.contact.email], ) msg.attach_alternative(email_html, "text/html") msg.send()
def run(): from accounts.models import Course accounts_course_1 = Course() accounts_course_1.code = u'MCA' accounts_course_1.name = u'MCA' accounts_course_1.duration = 3L accounts_course_1.level = u'PG' try: accounts_course_1.save() except IntegrityError: pass from accounts.models import Batch accounts_batch_1 = Batch() accounts_batch_1.code = u'09mca' accounts_batch_1.course = accounts_course_1 accounts_batch_1.year = 2009L accounts_batch_1.name = u'MCA 2009-2012 Batch' try: accounts_batch_1.save() except IntegrityError: pass from django.contrib.auth.models import User auth_user_2 = User() auth_user_2.username = settings.TEST_USERNAME auth_user_2.first_name = u'Test' auth_user_2.last_name = u'User' auth_user_2.email = u'' auth_user_2.is_staff = False auth_user_2.is_active = True auth_user_2.is_superuser = False try: auth_user_2.save() except IntegrityError: pass auth_user_2 = User.objects.get(username=settings.TEST_USERNAME) auth_user_2.set_password(settings.TEST_USER_PASSWORD) auth_user_2.save() from accounts.models import Profile accounts_profile_1 = Profile() accounts_profile_1.user = auth_user_2 accounts_profile_1.course = accounts_course_1 accounts_profile_1.year_of_joining = Decimal('2009') accounts_profile_1.college_email_id = u'*****@*****.**' accounts_profile_1.personal_email_id = u'*****@*****.**' accounts_profile_1.google_account_created = True accounts_profile_1.gender = u'M' accounts_profile_1.actual_date_of_birth = datetime.date(2009, 6, 1) try: accounts_profile_1.save() except IntegrityError: pass
def create_super_profile(**kwargs): for user in User.objects.filter(profile=None): # create profiles for all users that don't have profiles yet logger.info("\tcreating profile for super user: %s", user) profile = Profile(user=user) profile.save()
def organize_all(): from emencia.django.newsletter.models import Contact from django.contrib.auth.models import User from usermessage.models import UserMessage, StandardUserMessage from djangoratings.models import Vote, Score from book.models import Chapter from django.template import Context from django.template.loader import get_template from accounts.models import ScoreLog, Profile from simplewiki.models import Revision from django.contrib.comments.models import Comment from django.core.exceptions import ObjectDoesNotExist from BeautifulSoup import BeautifulSoup contacts = Contact.objects.all() staff_usermessages = weeklymessages = StandardUserMessage.objects.all() for contact in contacts: if contact.subscriber==True: comments_on_comments = UserMessage.objects.filter(contact=contact, category=1) comments_on_revisions = UserMessage.objects.filter(contact=contact, category=3) new_chapters = UserMessage.objects.filter(contact=contact, category=4) #revisions_on_revisions = UserMessage.objects.filter(contact=contact, category=2) #Only for users if contact.content_object: user = contact.content_object try: profile = user.get_profile() except ObjectDoesNotExist: p = Profile(user=user) p.save() submitted_chapters = Chapter.objects.filter(author=user) edited_chapters = Revision.objects.filter(revision_user=user).exclude(counter=1) commented_chapters = Comment.objects.filter(user=user).order_by('content_type') rated_chapters = Vote.objects.filter(user=user) given_positive_votes_on_comments = ScoreLog.objects.filter(profile=profile,points=1,ctype='vote') received_positive_votes_on_comments = ScoreLog.objects.filter(profile=profile,points=2,ctype='commentvoted') received_negative_votes_on_comments = ScoreLog.objects.filter(profile=profile,points=-1,ctype='commentvoted') else: user = None submitted_chapters = None edited_chapters = None commented_chapters = None rated_chapters = None given_positive_votes_on_comments = None received_positive_votes_on_comments = None received_negative_votes_on_comments = None #create message if any if comments_on_comments or comments_on_revisions or new_chapters or staff_usermessages or user: plaintext = get_template('email/weekly_newsletter.txt') html = get_template('email/weekly_newsletter.html') c = Context({ 'contact' : contact, 'comments_on_comments' : comments_on_comments, 'comments_on_revisions' : comments_on_revisions, 'new_chapters' : new_chapters, 'staff_usermessages' : staff_usermessages, 'user' : user, 'submitted_chapters' : submitted_chapters, 'edited_chapters' : edited_chapters, 'commented_chapters' : commented_chapters, 'rated_chapters' : rated_chapters, 'given_positive_votes_on_comments' : given_positive_votes_on_comments, 'received_positive_votes_on_comments' : received_positive_votes_on_comments, 'received_negative_votes_on_comments' : received_negative_votes_on_comments, }) email_plaintext = plaintext.render(c) email_html = html.render(c) #change header and link style soup = BeautifulSoup(email_html) for link_markup in soup('a'): link_markup['style'] = 'color:#16AAD7;' for header_markup in soup('h3'): header_markup['style'] = 'color:black;border-bottom:8px solid #ecebe8;margin-bottom:0px;padding-bottom:5px;' email_html = soup.prettify() final_mail = Message(to_address=contact.email, from_address='*****@*****.**', subject='Updates from winning-without-losing', message_text=email_plaintext, message_html=email_html ) final_mail.save() logging.info("Organizing message to %s" % final_mail.to_address.encode("utf-8")) comments_on_comments.delete() comments_on_revisions.delete() new_chapters.delete() staff_usermessages.delete()
def social_auth_complete(request, *args, **kwargs): response = social_complete(request, *args, **kwargs) if request.user.is_authenticated(): Profile.check_tz(request) return response