Beispiel #1
0
def contact_view(request):
    if request.user.is_authenticated():
        email = request.user.email
    else:
        email = None
    if request.method == 'POST':
        form = ContactForm(email=email, data=request.POST)
        if form.is_valid():
            subject = "Contact form: %s" % form.cleaned_data['subject']
            email = form.cleaned_data['email_address']
            body = render_to_string('emails/contact_form.txt',
                                    {'body': form.cleaned_data['body'],
                                     'email': email,
                                     'user': request.user})
            send_mail(
                subject=subject,
                message=body,
                from_email=email,
                recipient_list=settings.CONTACT_EMAILS,
            )
            messages.info(
                request,
                "Thank you!  Your message has been sent to the site administrators. "
                "If you have a question or problem, someone will contact you.")
            return redirect(request.path)
    else:
        form = ContactForm(email=email)
    return render(request, 'contact.html', {'form': form})
Beispiel #2
0
def attend(request, id):
  event = models.Event.objects.get(id=id)
  event.attendees.add(request.user.member)
  event.save()
  messages.info(request, "Your planned attendence is duly noted.")
  return HttpResponseRedirect(reverse('events:view', kwargs={'id':
    event.id}))
Beispiel #3
0
def create(request):
    # shipping_opts = shipping.util.get_session(request)
    initial = {
        # 'country': shipping_opts.get('country'),
    }

    if request.method == 'POST':
        account_form = AccountForm(request.POST, initial=initial)
        user_form = CreateUserForm(request.POST)
        if account_form.is_valid() and user_form.is_valid():
            account = account_form.save(commit=False)
            account.user = user_form.save()
            account.save()
            auth_user = authenticate(
                username=account.user.username,
                password=user_form.cleaned_data['password1'])
            login(request, auth_user)
            messages.info(request, 'Your account was created.')
            return redirect(details)
    else:
        account_form = AccountForm(initial=initial)
        user_form = CreateUserForm()

    return {
        'account_form': account_form,
        'user_form': user_form,
    }
Beispiel #4
0
def delete(request, message_id, success_url=None):
    """
    Marks a message as deleted by sender or recipient. The message is not
    really removed from the database, because two users must delete a message
    before it's save to remove it completely. 
    A cron-job should prune the database and remove old messages which are 
    deleted by both users.
    As a side effect, this makes it easy to implement a trash with undelete.
    
    You can pass ?next=/foo/bar/ via the url to redirect the user to a different
    page (e.g. `/foo/bar/`) than ``success_url`` after deletion of the message.
    """
    user = request.user
    now = datetime.datetime.now()
    message = get_object_or_404(Message, id=message_id)
    deleted = False
    if success_url is None:
        success_url = reverse('messages_inbox')
    if request.GET.has_key('next'):
        success_url = request.GET['next']
    if message.sender == user:
        message.sender_deleted_at = now
        deleted = True
    if message.recipient == user:
        message.recipient_deleted_at = now
        deleted = True
    if deleted:
        message.save()
        messages.info(request, _(u"Message successfully deleted."))
        if notification:
            notification.send([user], "messages_deleted", {'message': message,})
        return HttpResponseRedirect(success_url)
    raise Http404
Beispiel #5
0
def add_edit_contact(request, pk=None):
    _form = ContractorContactForm
    _model  = ContractorContact
    if pk is None:
        record  = _model()
        form = _form(request.POST or None)
    else:
        record  = get_object_or_404(_model, pk=pk)
        form = _form(initial=record.__dict__)

    if request.method == 'POST':
        form = _form(request.POST)
        if form.is_valid():
            form.get_cleaned_data('pic')
            populate_obj(form.cleaned_data, record)

            record.save()
            messages.info(request, "Successfully Updated the Database")

            return redirect('contract_mgt:table_contact')

    context = {
        'forms' : form,
        'form_title': 'Contractor Contact'
    }
    return render(request, 'default/add_form.html', context)
Beispiel #6
0
def TaskInstanceValidate(request, task_instance_id):
    task_instance = get_object_or_404(TaskInstance, pk=task_instance_id, task__owner=request.user)
    if request.POST:

        form = ValidationForm(request.POST)
        if form.is_valid():
            if 'validation' not in task_instance.parameters:
        # TODO: unify with the api, now the code is copied
                value = form.cleaned_data['validation']
                task_instance.quality = value
                pars = task_instance.parameters
                if pars is None:
                    pars = {}
                pars['validation'] = value
                task_instance.save()
                # if ("process_tactics_id" in task_instance.parameters):
                #     signal(task_instance.parameters['process_tactics_id'], task_instance.task.id, task_instance.id)
                messages.info(request, 'Validation made')
            else:
                messages.warning(request, 'Validation was already set')
            return redirect(reverse('r-taskinstances',args={task_instance.task.process.id,task_instance.task.id,}))
        else:
            return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
    else:
        form = ValidationForm()
        return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
 def can_edit(self, user=None, request=None):
     """
     Define if a user can edit or not the instance, according to his account
     or the request.
     """
     can = False
     if request and not self.owner:
         if (getattr(settings, "LEAFLET_STORAGE_ALLOW_ANONYMOUS", False)
                 and self.is_anonymous_owner(request)):
             can = True
             if user and user.is_authenticated():
                 # if user is authenticated, attach as owner
                 self.owner = user
                 self.save()
                 msg = _("Your anonymous map has been attached to your account %s" % user)
                 messages.info(request, msg)
     if self.edit_status == self.ANONYMOUS:
         can = True
     elif not user.is_authenticated():
         pass
     elif user == self.owner:
         can = True
     elif self.edit_status == self.EDITORS and user in self.editors.all():
         can = True
     return can
Beispiel #8
0
def user_unsubscribe_address(request, address_subscription_id):
    '''
    For logged-in users to unsubscribe an address
    '''
    address_subscription = get_object_or_404(AddressSubscription, id=address_subscription_id)
    assert address_subscription.auth_user == request.user

    if address_subscription.unsubscribed_at:
        msg = _("You've already unsubscribed from this alert")
        messages.info(request, msg)
    else:
        address_subscription.unsubscribed_at = now()
        address_subscription.save()

        address_uri = reverse('address_overview', kwargs={
            'coin_symbol': address_subscription.coin_symbol,
            'address': address_subscription.b58_address,
            })
        msg = _('You have been unsubscribed from notifications on <a href="%(address_uri)s">%(b58_address)s</a>' % {
            'b58_address': address_subscription.b58_address,
            'address_uri': address_uri,
            })
        messages.success(request, msg, extra_tags='safe')

    return HttpResponseRedirect(reverse('dashboard'))
Beispiel #9
0
def TaskValidate(request, task_id):
    log.debug("task_id %s - %s - %s" %(task_id,request.POST,request.GET))
    task = get_object_or_404(Task, pk=task_id, owner=request.user)

    if request.POST:

        form = ValidationForm(request.POST)
        if form.is_valid():
        # TODO: unify with the api, now the code is copied
            value = form.cleaned_data['validation']
            for task_instance in task.taskinstance_set.all():
                if 'validation' not in task_instance.parameters:
                    task_instance.quality = value
                    pars = task_instance.parameters
                    if pars is None:
                        pars = {}
                    pars['validation'] = value
                    task_instance.save()
                    # if ("process_tactics_id" in task_instance.parameters):
                    #     signal(task_instance.parameters['process_tactics_id'], task_instance.task.id, task_instance.id)
            messages.info(request, 'Validation made')
            return redirect(reverse('r-taskinstances',args={task_instance.task.process.id,task_instance.task.id,}))
        else:
            return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
    else:
        log.debug("GET task_id %s",task_id)
        form = ValidationForm()
        return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
Beispiel #10
0
def teacher_login(request):
	if request.user.is_authenticated():
		messages.info(request,'Please logout first and then re-login with a different account.')
		return HttpResponseRedirect('/home/')
	if request.method == 'POST':
		t_username = request.POST.get('username')
		t_password = request.POST.get('password')
		try:
			t_user = authenticate(username=t_username, password=t_password)
			teacher = Teacher.objects.get(pk=t_user.id)
		except Exception as e:
			t_user = None
			teacher = None
		if teacher is not None:
			if t_user.is_active:
				login(request, t_user)
				messages.success(request,'You logged in successfully.')
				return HttpResponseRedirect('/teacher/')
			else:
				messages.warning(request,'Your account is not yet active.')
				return render(request, 'teacher/login_teacher.html', {'t_not_active': True, 'next': request.POST.get('next')})
		else:
			course_list = CourseDetail.objects.all()
			course_list = pagination.get_paginated_list(obj_list=course_list,page = request.GET.get('page'))
			messages.error(request,'Please enter valid credentials.')
			return render(request, 'teacher/login_teacher.html', {'t_login_error': True, 'next': request.POST.get('next')})
	else:
		return render(request,'teacher/login_teacher.html',{})
Beispiel #11
0
def download_xls(request, course_uuid):

	course = CourseDetail.objects.get(course_uuid = course_uuid, teacher = request.user)
	# user_list = []
	if course:
		_users_enroll_course = EnrolledCourses.objects.filter(course = course)
		# user_list = [enroll_course.user for enroll_course in _users_enroll_course]

	try:
		assert _users_enroll_course,'Assert Error: Not have any user'
	except Exception as e:
		messages.info(request, 'Unable to find enrolled user(s) in this course.')
		return redirect('/teacher/manage/'+course_uuid)
	_sm_course_name = 'course_id_'+str(course.id)
	if create_users_xls(users_enroll_course = _users_enroll_course, _sm_course_name = _sm_course_name, course_name = course.course_name):
		dir_name = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
		file_dir_path = 'xls/'+_sm_course_name 
		filename = dir_name+'/'+file_dir_path+'/enrolled_user.xls'
		wrapper = FileWrapper(file(filename))
		response = HttpResponse(wrapper, content_type='text/plain')
		response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename)
		response['Content-Length'] = os.path.getsize(filename)
		return response
	else:
		messages.error(request,'Error in your request please try again after some time.')
		return redirect('/teacher/manage/'+course_uuid)
Beispiel #12
0
def signup(request):
    if request.method == 'POST':
        form = SignupForm2(request.POST)
        if form.is_valid():
            user = form.save()

            # backend_cls = get_backends()[0].__class__
            # backend_path = backend_cls.__module__ + '.' + backend_cls.__name__
            # https://github.com/django/django/blob/1.9/django/contrib/auth/__init__.py#L81
            # user.backend = backend_path

            authenticated_user = authenticate(
                    username=form.cleaned_data['username'],
                    password=form.cleaned_data['password1'])

            auth_login(request, authenticated_user)

            messages.info(request, '환영합니다. ;)')
            return redirect(settings.LOGIN_REDIRECT_URL)

            # 회원가입 시에, 이메일 승인
            # user = form.save(commit=False)
            # user.is_active = False
            # user.save()
            # send_signup_confirm_email(request, user)
            # return redirect(settings.LOGIN_URL)
    else:
        form = SignupForm2()
    return render(request, 'accounts/signup.html', {
        'form': form,
    })
Beispiel #13
0
def dump_fixtures(request):
    output = StringIO()

    fixture = request.GET.get('fixture', None)

    try:
        if fixture:
            call_command('dumpdata', fixture, '--indent=2', stdout=output)
        else:
            call_command('dumpdata', '--indent=2', stdout=output)

        data = output.getvalue()
        output.close()

        if fixture:
            file_label = 'fixtures_%s_%s' % (fixture, datetime.datetime.now().strftime('%d-%b-%Y_%H-%M'))
        else:
            file_label = 'fixtures_all_%s' % datetime.datetime.now().strftime('%d-%b-%Y_%H-%M')
        response = HttpResponse(data, content_type="application/json")
        response['Content-Disposition'] = 'attachment; filename=%s' % file_label
        return response
    except:
        dest =  request.META.get('HTTP_REFERER', '/')
        messages.info(request, 'Fixture name not recognized: %s' % fixture)
        return HttpResponseRedirect(dest)
Beispiel #14
0
def save_file(request):
    """
    The POST endpoint to save a file in the file editor.

    Does the save and then redirects back to the edit page.
    """
    form = EditorForm(request.POST)
    is_valid = form.is_valid()
    path = form.cleaned_data.get('path')

    if request.POST.get('save') == "Save As":
        if not is_valid:
            return edit(request, path, form=form)
        else:
            return render("saveas.mako", request, {'form': form})

    if not path:
        raise PopupException(_("No path specified"))
    if not is_valid:
        return edit(request, path, form=form)

    if request.fs.exists(path):
        do_overwrite_save(request.fs, path,
                           form.cleaned_data['contents'],
                           form.cleaned_data['encoding'])
    else:
        do_newfile_save(request.fs, path,
                         form.cleaned_data['contents'],
                         form.cleaned_data['encoding'])

    messages.info(request, _('Saved %(path)s.') % {'path': os.path.basename(path)})
    request.path = reverse("filebrowser.views.edit", kwargs=dict(path=path))
    return edit(request, path, form)
Beispiel #15
0
def _apply_changes(request, old_status, new_status):
    """Apply the changes"""
    modified = False

    if old_status['enabled'] != new_status['enabled']:
        sub_command = 'enable' if new_status['enabled'] else 'disable'
        actions.superuser_run('transmission', [sub_command])
        transmission.service.notify_enabled(None, new_status['enabled'])
        modified = True

    if old_status['download_dir'] != new_status['download_dir'] or \
       old_status['rpc_username'] != new_status['rpc_username'] or \
       old_status['rpc_password'] != new_status['rpc_password']:
        new_configuration = {
            'download-dir': new_status['download_dir'],
            'rpc-username': new_status['rpc_username'],
            'rpc-password': new_status['rpc_password'],
        }

        actions.superuser_run('transmission', ['merge-configuration'],
                              input=json.dumps(new_configuration).encode())
        modified = True

    if modified:
        messages.success(request, _('Configuration updated'))
    else:
        messages.info(request, _('Setting unchanged'))
Beispiel #16
0
 def get_object(self, *args, **kwargs):
     obj = self.model.objects.get(
         order=get_order(self.request),
         content_type=self.kwargs['content_type'],
         object_id=self.kwargs['object_id'])
     messages.info(self.request, _('%s removed' % obj))
     return obj
Beispiel #17
0
def test_view(request):
	for i in range(1,5):
		if random.random() > 0.5:
			messages.info(request, 'Error, dude!')
	breadcrumbs = [['Home', '/'], ['Away']]
			
	return render(request, 'test.html', {'breadcrumbs':breadcrumbs})
Beispiel #18
0
def complete_registration(request):
    if request.user.is_authenticated():
        return http.HttpResponseForbidden(u"Вы попали сюда по ошибке")
    try:
        identity_id = request.session.get("users_complete_reg_id", None)
        user_map = models.UserMap.objects.get(identity__id=identity_id)
    except models.UserMap.DoesNotExist:
        return http.HttpResponseForbidden(u"Вы попали сюда по ошибке")
    if request.method == "POST":
        form = CompleteReg(user_map.user.id, request.POST)
        if form.is_valid():
            user_map.user.username = form.cleaned_data["username"]
            user_map.user.email = form.cleaned_data["email"]
            user_map.user.save()

            user_map.verified = True
            user_map.save()

            user = auth.authenticate(user_map=user_map)
            auth.login(request, user)

            messages.info(request, u"Добро пожаловать!")
            del request.session["users_complete_reg_id"]
            return redirect(_return_path(request))
    else:
        form = CompleteReg(user_map.user.id, initial={"username": user_map.user.username, "email": user_map.user.email})

    return form
def url_inscripcion_extra(request, id_inscripto):
    m, txt = encode_data(str(id_inscripto))
    #url_info = request.scheme + '://' + request.META['HTTP_HOST'] + '/inscripto?m="' + m + '"&text="' + txt +'"'
    url_info = request.scheme + '://' + request.META['HTTP_HOST'] + '/inscripto?m=' + urllib.quote(m) + '&text=' + urllib.quote(txt)
    messages.info(request, url_info)
    inscripto = get_object_or_404(InscripcionBase, pk=id_inscripto)
    return inscriptos_actividad(request, inscripto.actividad.id)
Beispiel #20
0
 def send_mail(self, request):
     fn = self.cleaned_data['firstname']
     ln = self.cleaned_data['lastname']
     subj = self.cleaned_data['subject']
     fr = self.cleaned_data['email']
     msg = self.cleaned_data['message']
     try:
         requests.post(
             "https://api.mailgun.net/v2/neumerance.mailgun.org/messages",
             auth= ("api", "key-85jxyi84br32xu0cizfihmmbbxv576j5"),
             data={
                   "from":fr,
                   "to": ["*****@*****.**",],
                   "subject": subj,
                   "text": msg
             }
          )
         messages.info(request, 
                       "Thank you for sending me your feedback, I will get back to you as soon as possible.",
                       extra_tags="success"
                       )
     except:
         messages.info(request, 
                       "Unable to send your message at this time, Please try again later.",
                       extra_tags="error"
                       )
Beispiel #21
0
def most_relevant(request):
    session = Session()
    timer = datetime.now()
    join = sa_post.join(sa_relvote, onclause=(sa_relvote.c.post_id==sa_post.c.id))
    sel = select([sa_post.c.id, func.count(sa_relvote.c.id).label("votes")], whereclause=sa_relvote.c.date_expire > datetime.now(), 
            from_obj=[join]).group_by(sa_post.c.id).order_by("votes DESC")
    ps = session.execute(sel).fetchall()
    print ps
    delta = datetime.now() - timer
    print delta
    if not ps:
        messages.info(request, "This site has nothing relevant green vote on something")
    try:
        _id = ps[0][0]
        post = Post.objects.get(pk=_id)
    except:
        post = Post.objects.get(pk=1)
    temp_args = {'post' : post}
    children = list(Post.objects.filter(parent=post)\
            .annotate(num_votes=Count('vote'))\
            .order_by('-num_votes'))
    temp_args['p_struct'] = children
    temp_args['prof_user'] = request.user
    Session.remove()
    return render_to_response("most_relevant.html",
            temp_args,
            RequestContext(request))
Beispiel #22
0
def join_group(request, group_pk):
    """User request to join group."""
    group = get_object_or_404(Group, pk=group_pk)
    profile_to_add = request.user.userprofile

    # TODO: this duplicates some of the logic in Group.user_can_join(), but we
    # want to give the user a message that's specific to the reason they can't join.
    # Can we make this DRYer?

    if group.has_member(profile_to_add):
        messages.error(request, _('You are already in this group.'))
    elif group.has_pending_member(profile_to_add):
        messages.error(request, _('Your request to join this group is still pending.'))
    elif group.accepting_new_members == 'no':
        messages.error(request, _('This group is not accepting requests to join.'))
    else:
        if group.accepting_new_members == 'yes':
            group.add_member(profile_to_add)
            messages.info(request, _('You have been added to this group.'))
        elif group.accepting_new_members == 'by_request':
            group.add_member(profile_to_add, status=GroupMembership.PENDING)
            messages.info(request,
                          _('Your membership request is pending approval by the group curator.'))

    return redirect(reverse('groups:show_group', args=[group.url]))
Beispiel #23
0
def event_archive(request, id):
    """Dedicated page for setting page template (archive) and archive time."""
    event = Event.objects.get(id=id)
    if request.method == 'POST':
        form = forms.EventArchiveForm(request.POST, instance=event)
        if form.is_valid():
            event = form.save(commit=False)
            minutes = form.cleaned_data['archive_time']
            now = (datetime.datetime.utcnow()
                   .replace(tzinfo=utc, microsecond=0))
            event.archive_time = (
                now + datetime.timedelta(minutes=minutes)
            )
            event.save()
            messages.info(request, 'Event "%s" saved.' % event.title)
            return redirect('manage:events')
    else:
        form = forms.EventArchiveForm(instance=event)
    vidly_shortcut_form = forms.VidlyURLForm(
        initial=dict(email=request.user.email)
    )
    return render(request, 'manage/event_archive.html',
                  {'form': form,
                   'event': event,
                   'vidly_shortcut_form': vidly_shortcut_form})
Beispiel #24
0
	def post(self,request,*args,**kwargs):
		user_form = UserForm(request.POST)
		empleado_form = EmpleadoForm(request.POST,request.FILES)

		if user_form.is_valid() and empleado_form.is_valid():
			new_user = user_form.save()
			new_empleado = empleado_form.save()
			new_empleado.user = new_user
			new_empleado.save()
			messages.info(request,'Nuevo empleado creado con exito')

			url = reverse(
				'empleado:listar-empleados-sucursal',
				kwargs={'spk': new_empleado.sucursal.id})

			return HttpResponseRedirect(url)


		sucursal = Sucursal.objects.get(id=kwargs['spk'])
		user_form = UserForm(request.POST)
		empleado_form = EmpleadoForm(request.POST)


		messages.error(request,'Hay errores en algun campo, revise el formulario')

		context = {
		'section_title':'Nuevo Empleado',
		'sucursal':sucursal,
		'user_form':user_form,
		'empleado_form':empleado_form }

		return render_to_response(
			'empleado/empleado_form.html',
			context,
			context_instance=RequestContext(request))
Beispiel #25
0
def event_edit(request, id):
    """Edit form for a particular event."""
    event = get_object_or_404(Event, id=id)
    if (not request.user.has_perm('main.change_event_others') and
            request.user != event.creator):
        return redirect('manage:events')
    if request.user.has_perm('main.change_event_others'):
        form_class = forms.EventEditForm
    elif request.user.has_perm('main.add_event_scheduled'):
        form_class = forms.EventExperiencedRequestForm
    else:
        form_class = forms.EventRequestForm

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES, instance=event)
        if form.is_valid():
            event = form.save(commit=False)
            _event_process(request, form, event)
            event.save()
            form.save_m2m()
            messages.info(request, 'Event "%s" saved.' % event.title)
            return redirect('manage:events')
    else:
        timezone.activate(pytz.timezone('UTC'))
        form = form_class(instance=event, initial={
            'timezone': timezone.get_current_timezone()  # UTC
        })
    return render(request, 'manage/event_edit.html',
                  {'form': form, 'event': event})
Beispiel #26
0
def compose(request, recipient=None, form_class=ComposeForm,
        template_name='django_messages/compose.html', success_url=None, recipient_filter=None):
    """
    Displays and handles the ``form_class`` form to compose new messages.
    Required Arguments: None
    Optional Arguments:
        ``recipient``: username of a `django.contrib.auth` User, who should
                       receive the message, optionally multiple usernames
                       could be separated by a '+'
        ``form_class``: the form-class to use
        ``template_name``: the template to use
        ``success_url``: where to redirect after successfull submission
    """
    if request.method == "POST":
        sender = request.user
        form = form_class(request.POST, recipient_filter=recipient_filter)
        if form.is_valid():
            form.save(sender=request.user)
            messages.info(request, _(u"Message successfully sent."))
            if success_url is None:
                success_url = reverse('messages_inbox')
            if request.GET.has_key('next'):
                success_url = request.GET['next']
            return HttpResponseRedirect(success_url)
    else:
        form = form_class()
        if recipient is not None:
            recipients = [u for u in User.objects.filter(username__in=[r.strip() for r in recipient.split('+')])]
            form.fields['recipient'].initial = recipients
    return render_to_response(template_name, {
        'form': form,
    }, context_instance=RequestContext(request))
Beispiel #27
0
def reply(request, message_id, form_class=ComposeForm,
        template_name='django_messages/compose.html', success_url=None, 
        recipient_filter=None, quote_helper=format_quote):
    """
    Prepares the ``form_class`` form for writing a reply to a given message
    (specified via ``message_id``). Uses the ``format_quote`` helper from
    ``messages.utils`` to pre-format the quote. To change the quote format
    assign a different ``quote_helper`` kwarg in your url-conf.
    
    """
    parent = get_object_or_404(Message, id=message_id)
    
    if parent.sender != request.user and parent.recipient != request.user:
        raise Http404
    
    if request.method == "POST":
        sender = request.user
        form = form_class(request.POST, recipient_filter=recipient_filter)
        if form.is_valid():
            form.save(sender=request.user, parent_msg=parent)
            messages.info(request, _(u"Message successfully sent."))
            if success_url is None:
                success_url = reverse('messages_inbox')
            return HttpResponseRedirect(success_url)
    else:
        form = form_class(initial={
            'body': quote_helper(parent.sender, parent.body),
            'subject': _(u"Re: %(subject)s") % {'subject': parent.subject},
            'recipient': [parent.sender,]
            })
    return render_to_response(template_name, {
        'form': form,
    }, context_instance=RequestContext(request))
Beispiel #28
0
    def post(self, request, *args, **kwargs):
        """

        Establece el estado del proyecto a finalizado

        """
        #establece el estado de la solicitud a enviada
        proyecto_fin = get_object_or_404(Proyecto, pk=self.kwargs['pk'])
        #serie de validaciones 
        (validez, mensaje ) = self.valid_finalizar_proyecto(self.kwargs['pk'])
        
        if not validez:
            messages.error(request,mensaje )
            return redirect(get_url_edicion_actual(request, 0))
        
        #valida el estado del proyecto 
        if proyecto_fin.estado != Proyecto.E_INICIADO:
            messages.error(request, 'ERROR : El proyecto no fue iniciado o ya fue finalizado' )
            return redirect(get_url_edicion_actual(request, 0))
        
        proyecto_fin.estado = Proyecto.E_FINALIZADO
        proyecto_fin.fechafin = date.today()
        proyecto_fin.save()
        messages.info(request, mensaje )
        return redirect(get_url_edicion_actual(request, 0))
Beispiel #29
0
def undelete(request, message_id, success_url=None):
    """
    Recovers a message from trash. This is achieved by removing the
    ``(sender|recipient)_deleted_at`` from the model.
    """
    user = request.user
    message = get_object_or_404(Message, id=message_id)
    undeleted = False
    if success_url is None:
        success_url = reverse('messages_inbox')
    if request.GET.has_key('next'):
        success_url = request.GET['next']
    if message.sender == user:
        message.sender_deleted_at = None
        undeleted = True
    if message.recipient == user:
        message.recipient_deleted_at = None
        undeleted = True
    if undeleted:
        message.save()
        messages.info(request, _(u"Message successfully recovered."))
        if notification:
            notification.send([user], "messages_recovered", {'message': message,})
        return HttpResponseRedirect(success_url)
    raise Http404
Beispiel #30
0
def auth_page(request):
    response = HttpResponseRedirect(url_reverse('auth_page'))
    if request.method == 'POST':
        post_data = request.POST.dict()
        login = post_data.get('login')
        password = post_data.get('password')
        try:
            User.objects.get(username=login)
        except User.DoesNotExist:
            messages.error(request, 'No such user in system')
            return response

        user = auth.authenticate(username=login, password=password)
        if user and user.is_active:
            messages.success(request, 'Welcome to system')
            auth.login(request, user)
            response = HttpResponseRedirect(url_reverse('index'))
        elif user and not user.is_active:
            messages.info(request, 'Your profile is blocked.')
        else:
            messages.error(request, 'Wrong login or password')
    else:
        response = render(request, 'c_auth_page/auth_page.html',
                          {'title': 'Authentication'})
    return response
Beispiel #31
0
 def info(title, detail=None):
     messages.info(request, message(title, detail))
Beispiel #32
0
 def get_success_url(self):
     messages.info(self.request, "Promotion removed successfully")
     return reverse('dashboard:promotion-list-by-url',
                    kwargs={'path': self.object.page_url})
Beispiel #33
0
    def post(self, *args, **kwargs):
        form = CheckoutForm(self.request.POST or None)
        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            if form.is_valid():

                use_default_shipping = form.cleaned_data.get(
                    'use_default_shipping')
                if use_default_shipping:
                    print("Using the defualt shipping address")
                    address_qs = Address.objects.filter(user=self.request.user,
                                                        address_type='S',
                                                        default=True)
                    if address_qs.exists():
                        shipping_address = address_qs[0]
                        order.shipping_address = shipping_address
                        order.save()
                    else:
                        messages.info(self.request,
                                      "No default shipping address available")
                        return redirect('check-out')
                else:
                    print("User is entering a new shipping address")
                    shipping_address1 = form.cleaned_data.get(
                        'shipping_address')
                    shipping_address2 = form.cleaned_data.get(
                        'shipping_address2')
                    shipping_country = form.cleaned_data.get(
                        'shipping_country')
                    shipping_zip = form.cleaned_data.get('shipping_zip')

                    if is_valid_form(
                        [shipping_address1, shipping_country, shipping_zip]):
                        shipping_address = Address(
                            user=self.request.user,
                            street_address=shipping_address1,
                            apartment_address=shipping_address2,
                            country=shipping_country,
                            zip=shipping_zip,
                            address_type='S')
                        shipping_address.save()

                        order.shipping_address = shipping_address
                        order.save()

                        set_default_shipping = form.cleaned_data.get(
                            'set_default_shipping')
                        if set_default_shipping:
                            shipping_address.default = True
                            shipping_address.save()

                    else:
                        messages.info(
                            self.request,
                            "Please fill in the required shipping address fields"
                        )

                use_default_billing = form.cleaned_data.get(
                    'use_default_billing')
                same_billing_address = form.cleaned_data.get(
                    'same_billing_address')

                if same_billing_address:
                    billing_address = shipping_address
                    billing_address.pk = None
                    billing_address.save()
                    billing_address.address_type = 'B'
                    billing_address.save()
                    order.billing_address = billing_address
                    order.save()

                elif use_default_billing:
                    print("Using the defualt billing address")
                    address_qs = Address.objects.filter(user=self.request.user,
                                                        address_type='B',
                                                        default=True)
                    if address_qs.exists():
                        billing_address = address_qs[0]
                        order.billing_address = billing_address
                        order.save()
                    else:
                        messages.info(self.request,
                                      "No default billing address available")
                        return redirect('check-out')
                else:
                    print("User is entering a new billing address")
                    billing_address1 = form.cleaned_data.get('billing_address')
                    billing_address2 = form.cleaned_data.get(
                        'billing_address2')
                    billing_country = form.cleaned_data.get('billing_country')
                    billing_zip = form.cleaned_data.get('billing_zip')

                    if is_valid_form(
                        [billing_address1, billing_country, billing_zip]):
                        billing_address = Address(
                            user=self.request.user,
                            street_address=billing_address1,
                            apartment_address=billing_address2,
                            country=billing_country,
                            zip=billing_zip,
                            address_type='B')
                        billing_address.save()

                        order.billing_address = billing_address
                        order.save()

                        set_default_billing = form.cleaned_data.get(
                            'set_default_billing')
                        if set_default_billing:
                            billing_address.default = True
                            billing_address.save()

                    else:
                        messages.info(
                            self.request,
                            "Please fill in the required billing address fields"
                        )

                payment_option = form.cleaned_data.get('payment_option')

                if payment_option == 'S':
                    return redirect('payment', payment_option='stripe')
                elif payment_option == 'P':
                    return redirect('payment', payment_option='paypal')
                else:
                    messages.warning(self.request,
                                     "Invalid payment option selected")
                    return redirect('check-out')
        except ObjectDoesNotExist:
            messages.warning(self.request, "You do not have an active order")
            return redirect("order-summary")
Beispiel #34
0
 def get(self, request, *args, **kwargs):
     shop = Shop.objects.filter(pk=kwargs.get("pk")).first()
     set_shop(request, shop)
     messages.info(request, (_("Shop {} is now active!")).format(shop.name))
     return HttpResponseRedirect(
         request.META.get("HTTP_REFERER", reverse("shuup_admin:home")))
Beispiel #35
0
def search(request):
    # TODO: used forms in every search type

    def _render_search_form(form=None):
        return render(request, 'djangobb_forum/search_form.html', {
            'categories': Category.objects.all(),
            'form': form,
        })

    if not 'action' in request.GET:
        return _render_search_form(form=PostSearchForm())

    if request.GET.get("show_as") == "posts":
        show_as_posts = True
        template_name = 'djangobb_forum/search_posts.html'
    else:
        show_as_posts = False
        template_name = 'djangobb_forum/search_topics.html'

    context = {}

    # Create 'user viewable' pre-filtered topics/posts querysets
    viewable_category = Category.objects.all()
    topics = Topic.objects.all().order_by("-last_post__created")
    posts = Post.objects.all().order_by('-created')
    user = request.user
    if not user.is_superuser:
        user_groups = user.groups.all() or [
        ]  # need 'or []' for anonymous user otherwise: 'EmptyManager' object is not iterable
        viewable_category = viewable_category.filter(
            Q(groups__in=user_groups) | Q(groups__isnull=True))

        topics = Topic.objects.filter(forum__category__in=viewable_category)
        posts = Post.objects.filter(
            topic__forum__category__in=viewable_category)

    base_url = None
    _generic_context = True

    action = request.GET['action']
    if action == 'show_24h':
        date = timezone.now() - timedelta(days=1)
        if show_as_posts:
            context["posts"] = posts.filter(
                Q(created__gte=date) | Q(updated__gte=date))
        else:
            context["topics"] = topics.filter(
                Q(last_post__created__gte=date)
                | Q(last_post__updated__gte=date))
        _generic_context = False
    elif action == 'show_new':
        if not user.is_authenticated:
            raise Http404(
                "Search 'show_new' not available for anonymous user.")
        try:
            last_read = PostTracking.objects.get(user=user).last_read
        except PostTracking.DoesNotExist:
            last_read = None

        if last_read:
            if show_as_posts:
                context["posts"] = posts.filter(
                    Q(created__gte=last_read) | Q(updated__gte=last_read))
            else:
                context["topics"] = topics.filter(
                    Q(last_post__created__gte=last_read)
                    | Q(last_post__updated__gte=last_read))
            _generic_context = False
        else:
            #searching more than forum_settings.SEARCH_PAGE_SIZE in this way - not good idea :]
            topics_id = [
                topic.id for topic in topics[:forum_settings.SEARCH_PAGE_SIZE]
                if forum_extras.has_unreads(topic, user)
            ]
            topics = Topic.objects.filter(
                id__in=topics_id)  # to create QuerySet

    elif action == 'show_unanswered':
        topics = topics.filter(post_count=1)
    elif action == 'show_subscriptions':
        topics = topics.filter(subscribers__id=user.id)
    elif action == 'show_user':
        # Show all posts from user or topics started by user
        if not user.is_authenticated:
            raise Http404(
                "Search 'show_user' not available for anonymous user.")

        user_id = request.GET.get("user_id", user.id)
        try:
            user_id = int(user_id)
        except ValueError:
            raise SuspiciousOperation()

        if user_id != user.id:
            try:
                search_user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                messages.error(request, _("Error: User unknown!"))
                return HttpResponseRedirect(request.path)
            messages.info(
                request,
                _("Filter by user '%(username)s'.") %
                {'username': search_user.username})

        if show_as_posts:
            posts = posts.filter(user__id=user_id)
        else:
            # show as topic
            topics = topics.filter(posts__user__id=user_id).order_by(
                "-last_post__created").distinct()

        base_url = "?action=show_user&user_id=%s&show_as=" % user_id
    elif action == 'search':
        form = PostSearchForm(request.GET)
        if not form.is_valid():
            return _render_search_form(form)

        keywords = form.cleaned_data['keywords']
        author = form.cleaned_data['author']
        forum = form.cleaned_data['forum']
        search_in = form.cleaned_data['search_in']
        sort_by = form.cleaned_data['sort_by']
        sort_dir = form.cleaned_data['sort_dir']

        query = SearchQuerySet().models(Post)

        if author:
            query = query.filter(author__username=author)

        if forum != '0':
            query = query.filter(forum__id=forum)

        if keywords:
            if search_in == 'all':
                query = query.filter(SQ(topic=keywords) | SQ(text=keywords))
            elif search_in == 'message':
                query = query.filter(text=keywords)
            elif search_in == 'topic':
                query = query.filter(topic=keywords)

        order = {
            '0': 'created',
            '1': 'author',
            '2': 'topic',
            '3': 'forum'
        }.get(sort_by, 'created')
        if sort_dir == 'DESC':
            order = '-' + order

        post_pks = query.values_list("pk", flat=True)

        if not show_as_posts:
            # TODO: We have here a problem to get a list of topics without double entries.
            # Maybe we must add a search index over topics?

            # Info: If whoosh backend used, setup HAYSTACK_ITERATOR_LOAD_PER_QUERY
            #    to a higher number to speed up
            context["topics"] = topics.filter(posts__in=post_pks).distinct()
        else:
            # FIXME: How to use the pre-filtered query from above?
            posts = posts.filter(pk__in=post_pks).order_by(order)
            context["posts"] = posts

        get_query_dict = request.GET.copy()
        get_query_dict.pop("show_as")
        base_url = "?%s&show_as=" % get_query_dict.urlencode()
        _generic_context = False

    if _generic_context:
        if show_as_posts:
            context["posts"] = posts.filter(
                topic__in=topics).order_by('-created')
        else:
            context["topics"] = topics

    if base_url is None:
        base_url = "?action=%s&show_as=" % action

    if show_as_posts:
        context['posts_page'] = get_page(context['posts'], request,
                                         forum_settings.SEARCH_PAGE_SIZE)
        context["as_topic_url"] = base_url + "topics"
        post_count = context["posts"].count()
        messages.success(request, _("Found %i posts.") % post_count)
    else:
        context['topics_page'] = get_page(context['topics'], request,
                                          forum_settings.SEARCH_PAGE_SIZE)
        context["as_post_url"] = base_url + "posts"
        topic_count = context["topics"].count()
        messages.success(request, _("Found %i topics.") % topic_count)

    return render(request, template_name, context)
Beispiel #36
0
    def post(self, *args, **kwargs):
        form = CheckoutForm(self.request.POST or None)
        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            if form.is_valid():

                use_default_address = form.cleaned_data.get(
                    'use_default_address')
                if use_default_address:
                    print("Using the defualt  address")
                    address_qs = Address.objects.filter(
                        user=self.request.user,
                        
                        default=True
                    )
                    if address_qs.exists():
                        address = address_qs[0]
                        order.address = address
                        order.save()
                    else:
                        messages.info(
                            self.request, "No default  address available")
                        return redirect('product:checkout')
                else:
                    print("User is entering a new  address")
                    house = form.cleaned_data.get(
                        'house')
                    street = form.cleaned_data.get(
                        'street')
                    landmark = form.cleaned_data.get(
                        'landmark')
                    city = form.cleaned_data.get(
                        'city')
                    zip = form.cleaned_data.get('zip')
                    mobile = form.cleaned_data.get('mobile')
                    set_default_address = form.cleaned_data.get('set_default_address')

                    if set_default_address:
                        address = Address(user=self.request.user,house_number=house,street_address=street,landmark=landmark,city=city,zip=zip,mobile_number=mobile,default =True)
                    else:
                        address = Address(user=self.request.user,house_number=house,street_address=street,landmark=landmark,city=city,zip=zip,mobile_number=mobile)
                    
                    address.save()

                    order.address =address
                    order.save()

                    
                            
                    
                    # address.save()
                        

                    # else:
                    #     messages.info(
                    #         self.request, "Please fill in the required  address fields")

                

                

                
                    
                   
                

                    
                        

                payment_option = form.cleaned_data.get('payment_option')

                if payment_option == 'S':
                    return redirect('product:payment', payment_option='stripe')
                elif payment_option == 'P':
                    return redirect('product:payment', payment_option='paypal')
                else:
                    messages.warning(
                        self.request, "Invalid payment option selected")
                    return redirect('product:checkout')
        except ObjectDoesNotExist:
            messages.warning(self.request, "You do not have an active order")
            return redirect("product:order-summary")
Beispiel #37
0
def qdele(request):
    id_del = request.POST.get('id1')
    id_colum = request.POST.get('id2')
    sql_text = str(request.POST.get('sql_text'))
    
    if id_colum == 'b_id':
        try:
            conn = psycopg2.connect(host="localhost",database="book1", user="******", password="******")
            conn.set_client_encoding('UTF8')
            cur = conn.cursor()
            sql_delete_query = """Delete from book where b_id = %s"""
            cur.execute(sql_delete_query, (str(id_del), ))
            conn.commit()
            count = cur.rowcount
            print(count, "Record deleted successfully ")
            messages.info(request, "Record deleted successfully ")
            return redirect('/query')
        except (Exception, psycopg2.Error) as error:
            print("Error in Delete operation", error)
            messages.info(request, "Error in Delete operation")
            return redirect('/query')

        finally:
            # closing database connection.
            if (conn):
                cur.close()
                conn.close()
                print("PostgreSQL connection is closed")
                # messages.info(request, "PostgreSQL connection is closed")
                return redirect('/query')
    if id_colum == 'a_name':
        try:
            conn = psycopg2.connect(host="localhost",database="book1", user="******", password="******")
            conn.set_client_encoding('UTF8')
            cur = conn.cursor()
            # Update single record now
            sql_delete_query = """Delete from author where a_name = %s"""
            cur.execute(sql_delete_query, (str(id_del), ))
            conn.commit()
            count = cur.rowcount
            print(count, "Record deleted successfully ")
            messages.info(request, "Record deleted successfully ")
            return redirect('/query')
        except (Exception, psycopg2.Error) as error:
            print("Error in Delete operation", error)
            messages.info(request, "Error in Delete operation")
            return redirect('/query')

        finally:
            # closing database connection.
            if (conn):
                cur.close()
                conn.close()
                print("PostgreSQL connection is closed")
                messages.info(request, "PostgreSQL connection is closed")
                return redirect('/query')
    if id_colum == 'p_name':
        try:
            conn = psycopg2.connect(host="localhost",database="book1", user="******", password="******")
            conn.set_client_encoding('UTF8')
            cur = conn.cursor()
            # Update single record now
            sql_delete_query = """Delete from publisher where p_name = %s"""
            cur.execute(sql_delete_query, (str(id_del), ))
            conn.commit()
            count = cur.rowcount
            print(count, "Record deleted successfully ")
            messages.info(request, "Record deleted successfully ")
            return redirect('/query')

        except (Exception, psycopg2.Error) as error:
            print("Error in Delete operation", error)
            messages.info(request, "Error in Delete operation")
            return redirect('/query')

        finally:
            # closing database connection.
            if (conn):
                cur.close()
                conn.close()
                print("PostgreSQL connection is closed")
                # messages.info(request, "PostgreSQL connection is closed")
                return redirect('/query')


    messages.info(request, str(id_del)+str(id_colum))
    print(id_del)
    print(sql_text)
    return redirect('/query')
Beispiel #38
0
def search(request):
    """
    Searches through following fields:
        - Post teaser
        - Blogger last_name
        - AffilatedBlog blogname
        - Exact matches if input is given between quotes ' or "
    Return list of alumni with all thesis links"""

    words = request.GET.get("terms", "")
    terms, posts, bloggers, affiliated_blogs = [], [], [], []

    if len(words) <= 2:
        messages.error(request,
                       "Error: Please use at least 3 characters to search.")
        messages.info(
            request,
            "Tip: you can use exact match by placing ' or \" around words!")
        return render(
            request,
            "search/search_results.html",
            {
                "posts": posts,
                "bloggers": bloggers,
                "affiliated_blogs": affiliated_blogs,
                "key_words": terms,
            },
        )

    if len(words.split()) > 10:
        messages.error(request,
                       "Error: Please limit your search to <10 words.")
        messages.info(
            request,
            "Tip: you can use exact match by placing ' or \" around words!")
        return render(
            request,
            "search/search_results.html",
            {
                "posts": posts,
                "bloggers": bloggers,
                "affiliated_blogs": affiliated_blogs,
                "key_words": terms,
            },
        )

    # Check if must be exact match (i.e. if between quotation marks)
    words = words.replace("'", '"')
    if '"' in words:
        exact_match = re.findall('"([^"]*)"', words)

        for exact in exact_match:
            words.replace(exact, "")
            terms.append(exact)

    # Create final lists of search terms
    terms = terms + words.split()

    #  Remove single characters
    terms = [term for term in terms if len(term) > 1]

    # Compute filters
    posts_filter = Q()
    bloggers_filter = Q()
    affiliated_blogs_filter = Q()
    all_posts = Post.objects.filter(is_published=True)
    all_bloggers = Blogger.objects.all()
    all_affiliated_blogs = AffiliatedBlog.objects.all()

    for term in terms:
        posts_filter = (posts_filter
                        | Q(teaser__icontains=term)
                        | Q(url__icontains=term)
                        | Q(title__icontains=term))

        bloggers_filter = (bloggers_filter
                           | Q(first_name__icontains=term)
                           | Q(last_name__icontains=term)
                           | Q(affiliation__blogname__icontains=term))

        affiliated_blogs_filter = (affiliated_blogs_filter
                                   | Q(blogname__icontains=term)
                                   | Q(url__icontains=term))

    # Apply all filters
    posts = all_posts.filter(posts_filter).distinct()
    bloggers = all_bloggers.filter(bloggers_filter).distinct()
    affiliated_blogs = all_affiliated_blogs.filter(
        affiliated_blogs_filter).distinct()

    return render(
        request,
        "search/search_results.html",
        {
            "posts": posts,
            "bloggers": bloggers,
            "affiliated_blogs": affiliated_blogs,
            "key_words": terms,
        },
    )
Beispiel #39
0
def topic_review(request,
                 pk=0,
                 learn_more=False,
                 template_name='ucm/topic_review.html'):
    context = {'ptitle': "Review"}
    filters = Q()
    if request.method == 'GET':
        # 1. Check in the learning deck for pendng cards
        # 2. If pending found, proceed
        # 3. If no pending,
        # 3.1 If curr date is same as modified date in user topic, then ask user whether to create next learning deck
        # 3.2 If curr date is not same, create new learning deck
        print('User---------> ', request.user)
        ut = UserTopic.objects.filter(id=pk, user=request.user).first()
        if not ut:
            messages.info(request, "Not a subscribed topic")
            return render(request, template_name, {
                'flag': 'not_subscribed',
                'topic': pk,
                'context': context
            })

        filters = Q(
            Q(usernotem__usertopic_id=pk))  # & Q(usernotem__currdeck=1))
        uld = UserLearningDeck.objects.filter(filters).first()
        if not uld:
            if datetime.strftime(
                    timezone.now(), '%Y%m-%d') == datetime.strftime(
                        ut.mdate, '%Y%m-%d') and learn_more == False:
                messages.success(request,
                                 "You have no cards pending to learn today")
                return render(request, template_name, {
                    'flag': 'learn_more',
                    'topic': pk,
                    'context': context
                })
            else:
                if not learn_more:
                    messages.success(request,
                                     "Creating new learning deck for today")
                decksToLearn = do_calc(ut)
                i = 0
                for deck in decksToLearn:
                    unm = UserNotem.objects.filter(
                        usertopic_id=pk,
                        currdeck=deck['currdeck'])[:deck['newCount']]
                    print("Adding from deck [", deck['currdeck'], "] ",
                          deck['newCount'], "cards")
                    for un in unm:
                        i += 1
                        UserLearningDeck.objects.create(usernotem=un,
                                                        cuser=request.user)

                if i == 0:
                    messages.info(
                        request, "Your topic has no more cards left to learn")
                    return render(request, template_name, {
                        'flag': 'no_more',
                        'topic': pk
                    })
                else:
                    messages.success(
                        request,
                        'Added ' + str(i) + ' cards to your learning deck')
    else:
        raise Http404

    # rand_id = random.randint(1, 100)
    ob = ['usernotem__mdate']
    uld = UserLearningDeck.objects.filter(filters).order_by(*ob).first()
    # print (userNote)
    # print ('ULD ID:', userNote.usernotem.id, 'usernotem.notem:', userNote.usernotem.notem.id)
    note = None
    formReviewLog = ''
    if not uld:
        print('Qeury returned 0 rows')


#		messages.error (request, 'Not found [notem_id=' + str (pk) + '] [currdeck=0]')
    else:
        ob = ['norder']
        nd = Noted.objects.filter(notem__id=uld.usernotem.notem.id).order_by(
            *ob).prefetch_related('notem')
        if nd:
            print(nd)
        else:
            print('no such note')

        ob = [
            '-cdate',
        ]
        reviewLog = ReviewLog.objects.filter(
            usernotem=uld.usernotem.id).order_by(*ob)
        formReviewLog = ReviewLogForm(initial={
            'usernotem': uld.usernotem,
            'cuser': request.user
        })

    return render(
        request, template_name, {
            'userNote': uld,
            'note': nd,
            'topic': pk,
            'reviewLog': reviewLog,
            'formReviewLog': formReviewLog,
            'context': context
        })
Beispiel #40
0
def login(request, on_failure='im/login.html'):
    """
    on_failure: the template name to render on login failure
    """
    if request.method == 'GET':
        return HttpResponseRedirect(reverse('login'))

    was_limited = getattr(request, 'limited', False)
    form = LoginForm(data=request.POST,
                     was_limited=was_limited,
                     request=request)
    next = get_query(request).get('next', '')
    third_party_token = get_query(request).get('key', False)
    provider = auth.get_provider('local')

    if not form.is_valid():
        if third_party_token:
            messages.info(request, provider.get_login_to_add_msg)

        return render_to_response(
            on_failure,
            {'login_form':form,
             'next':next,
             'key': third_party_token},
            context_instance=RequestContext(request))

    # get the user from the cache
    user = form.user_cache
    provider = auth.get_provider('local', user)

    if not provider.get_login_policy:
        message = provider.get_login_disabled_msg
        messages.error(request, message)
        return HttpResponseRedirect(reverse('login'))

    message = None
    if not user:
        message = provider.get_authentication_failed_msg
    elif not user.is_active:
        message = user.get_inactive_message('local')

    elif not user.has_auth_provider('local'):
        # valid user logged in with no auth providers set, add local provider
        # and let him log in
        if not user.get_available_auth_providers():
            user.add_auth_provider('local')
        else:
            message = _(astakos_messages.NO_LOCAL_AUTH)

    if message:
        messages.error(request, message)
        return render_to_response(on_failure,
                                  {'login_form': form},
                                  context_instance=RequestContext(request))

    response = prepare_response(request, user, next)
    if third_party_token:
        # use requests to assign the account he just authenticated with with
        # a third party provider account
        try:
            request.user.add_pending_auth_provider(third_party_token)
        except PendingThirdPartyUser.DoesNotExist:
            provider = auth.get_provider('local', request.user)
            messages.error(request, provider.get_add_failed_msg)

    provider = user.get_auth_provider('local')
    messages.success(request, provider.get_login_success_msg)
    response.set_cookie('astakos_last_login_method', 'local')
    return response
def approve_request(request, order_id):
    app_req = CancelledApproval.objects.get(order_id=order_id)
    can_req = CancelledOrder.objects.get(order_id=order_id)
    ord_req = Order.objects.get(order_id=order_id)

    emailapp = Email.objects.get(email_id=3)
    emailrej = Email.objects.get(email_id=4)


    if request.POST.get('approve'):

        template = get_template('orders/cancellationapproval.html')
        data = {
        "order_id": str(ord_req.order_id),
        "user": ord_req.user.username,
        "order_date":app_req.order_date,
        "cancelled_order_date":app_req.cancelled_order_date,
        "course_price":app_req.amount,
        "order_amount":app_req.final_amount,
        "refund_amount":app_req.refund_amount,
        }
        html = template.render(data)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        pdf = result.getvalue()
        filename = 'Invoice_' + data['order_id'] + '.pdf'
        template = get_template('orders/cancellationapproval.html')

        # Email to customer for order cancellation approval
        email = EmailMessage(
            emailapp.email_subject,
            emailapp.email_body.format(ord_req.user.username, ord_req.course.product_name, ord_req.order_id, app_req.refund_amount),
            emailapp.email_sender,
            [app_req.user.email, '*****@*****.**'])
        email.attach(filename, pdf, 'application/pdf')
        email.send()

        app_req.delete()
        can_req.delete()
        ord_req.delete()
        messages.info(request, "Order cancellation approved!!! Customer has been notified via email.")
        return redirect('orders:approvalrequestsall')
        

    if request.POST.get('reject'):

        template = get_template('orders/cancellationrejection.html')
        data = {
        "order_id": str(ord_req.order_id),
        "user": ord_req.user.username,
        "order_date":app_req.order_date,
        "cancelled_order_date":app_req.cancelled_order_date,
        "amount":app_req.amount,
        "refund_amount":app_req.refund_amount,
        }
        html = template.render(data)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        pdf = result.getvalue()
        filename = 'Invoice_' + data['order_id'] + '.pdf'
        template = get_template('orders/cancellationrejection.html')

        # Email to customer for order cancellation rejection
        email = EmailMessage(
        emailrej.email_subject,
        emailrej.email_body.format(ord_req.user.username, ord_req.course.product_name, ord_req.order_id,app_req.refund_amount),
        emailrej.email_sender,
        [app_req.user.email, '*****@*****.**'])
        email.attach(filename, pdf, 'application/pdf')
        email.send()

        app_req.delete()
        can_req.delete()
        ord_req.delete()
        messages.info(request, "Order cancellation rejected!!! Customer has been notified via email.")
        return redirect('orders:approvalrequestsall')

    return redirect('orders:approvalrequestsall')
Beispiel #42
0
def logout_request(request):
    logout(request)
    messages.info(request, "Logged out successfully!")
    return redirect("/")
Beispiel #43
0
def delete(request, id):
    task = get_object_or_404(Task, pk=id)
    task.delete()
    messages.info(request, 'Tarefa excluída com sucesso!')
    return redirect('/')
def signup(request):
    if request.method == 'POST':
        get_otp =  request.POST.get('otp')
        if get_otp:
            get_user = request.POST.get('user')
            user = User.objects.get(username=get_user)
            if int(get_otp) == UserOTP.objects.filter(user=user).last().otp:
                user.is_active = True
                user.save()
                mess_two = f"Hello {user.first_name},\n\nYou have successfully created your account.\n\nThanks!\nDeveloper,\nFace Recognition App"
                send_mail(
                    "Welcome to Face Recognition App",
                    mess_two,
                    settings.EMAIL_HOST_USER,
                    [user.email],
                    fail_silently = False
                )
                messages.info(request, f'Account created for {user.username}')
                return redirect('/')
            else:
                messages.error(request, 'Invalid OTP, Please check your Email and varify')
                return render(request,'login_signup/signup.html', {'otp':True, 'user':user })

        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        username = request.POST.get('username')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')
        email = request.POST.get('email')
        
        if password1==password2:
            if User.objects.filter(username=username).exists():
                messages.info(request,'Username already exits !')
                return redirect('/signup/')
            elif User.objects.filter(email=email).exists():
                messages.info(request,'Email already exits !')
                return redirect('/signup/')
            else:
                user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name)
                user.is_active = False
                user.save()
                user_otp = int(random.randint(1000, 9999))
                UserOTP.objects.create(user=user, otp=user_otp)
                
                mess = f"Hello {user.first_name},\nYour OTP is: {user_otp} \n\nThanks!\nDeveloper,\nFace Recognition App"
                send_mail(
                    "Varify Your Email-Face Recognition App",
                    mess,
                    settings.EMAIL_HOST_USER,
                    [user.email],
                    fail_silently = False
                )
                messages.info(request, 'OTP sent, Check your Email and varify')
                return render(request,'login_signup/signup.html', {'otp':True, 'user':user })

                # messages.success(request,'User Registration successfully Completed. Please Login.')
        else:
            messages.info(request,'Password not matching !')
            return redirect('/signup/')
        return redirect('/')
    else:
        return render(request,'login_signup/signup.html')
Beispiel #45
0
    def form_valid(self, form):

        user = self.request.user

        validation = Validation.objects\
            .filter(pk=self.kwargs['pk'])\
            .prefetch_related('content')\
            .prefetch_related('content__authors')\
            .last()

        if not validation:
            raise PermissionDenied

        if validation.status not in ['PENDING', 'PENDING_V']:
            raise PermissionDenied  # cannot cancel a validation that is already accepted or rejected

        if user not in validation.content.authors.all(
        ) and not user.has_perm('tutorialv2.change_validation'):
            raise PermissionDenied

        versioned = validation.content.load_version(sha=validation.version)

        # reject validation:
        quote = '\n'.join(
            ['> ' + line for line in form.cleaned_data['text'].split('\n')])
        validation.status = "CANCEL"
        validation.comment_authors += _(u'\n\nLa validation a été **annulée** pour la raison suivante :\n\n{}')\
            .format(quote)
        validation.date_validation = datetime.now()
        validation.save()

        validation.content.sha_validation = None
        validation.content.save()

        # warn the former validator that the all thing have been canceled
        if validation.validator:
            bot = get_object_or_404(
                User, username=settings.ZDS_APP['member']['bot_account'])
            msg = render_to_string(
                'tutorialv2/messages/validation_cancel.md', {
                    'content':
                    versioned,
                    'validator':
                    validation.validator.username,
                    'url':
                    versioned.get_absolute_url() + '?version=' +
                    validation.version,
                    'user':
                    self.request.user,
                    'message':
                    quote
                })

            send_mp(
                bot,
                [validation.validator],
                _(u"Demande de validation annulée").format(),
                versioned.title,
                msg,
                False,
            )

        messages.info(self.request,
                      _(u'La validation de ce contenu a bien été annulée.'))

        self.success_url = reverse("content:view", args=[validation.content.pk, validation.content.slug]) + \
            "?version=" + validation.version

        return super(CancelValidation, self).form_valid(form)
Beispiel #46
0
def senddata(request):
    if request.method == 'POST':
        print("senddata")
        MediumName=(request.POST.get('MediumName'))
        print(MediumName)
        if MediumName:
            print("Hey")
        else:
            print("No Mediumname!!")
            messages.info(request, 'OIDA!')
            return redirect(reverse('IndexView') + '#get')
        message=(request.POST.get('Message'))
        FreeOrEmployed=(request.POST.get('FreeOrEmployed'))
        print(request.POST)
        try:
            mediumobj=Medium.objects.get(
            Q(mediumname=MediumName),
            Q(freeoremployed=FreeOrEmployed)
        )
            print("Found it")

            print(mediumobj)
            if FreeOrEmployed=="fest":
                SalaryPerMonthEmpMix=(request.POST.get('SalaryPerMonthEmpMix'))
                Happiness=(request.POST.get("Happiness"))
                d = mediumobj.datacollection_set.create(SalaryPerMonthEmpMix=int(SalaryPerMonthEmpMix),Happiness=int(Happiness)
                )

            if FreeOrEmployed=="pauschal":
                SalaryPerMonthEmpMix=(request.POST.get('SalaryPerMonthEmpMix'))
                Happiness=(request.POST.get("Happiness"))
                d = mediumobj.datacollection_set.create(SalaryPerMonthEmpMix=int(SalaryPerMonthEmpMix),Happiness=int(Happiness)
                )

            if FreeOrEmployed=="frei":
                gehalt=(request.POST.get('gehalt'))
                print(gehalt)
                wohlfuehl=(request.POST.get("happiness"))
                print(wohlfuehl)
                d = mediumobj.datacollection_set.create(salary_number=int(gehalt),rating_number=int(wohlfuehl)
                )

        except Medium.DoesNotExist:
            if FreeOrEmployed=="fest":
                SalaryPerMonthEmp=(request.POST.get('SalaryPerMonthEmp'))
                HoursPerWeekEmp=(request.POST.get("HoursPerWeekEmp"))
                JobPosition=(request.POST.get("JobPosition"))
                Experience=(request.POST.get("ExperienceEmplMix"))
                Happiness=(request.POST.get("Happiness"))
                comment=(request.POST.get("Message"))
                mediumobj = Medium(mediumname=MediumName, freeoremployed=FreeOrEmployed)
                mediumobj.save()

                d = mediumobj.datacollection_set.create(
                SalaryPerMonthEmp=int(SalaryPerMonthEmp),
                HoursPerWeekEmp=int(HoursPerWeekEmp),
                JobPosition=str(JobPosition),
                Experience=str(Experience),
                Happiness=int(Happiness),
                comment=str(comment),
                )



            if FreeOrEmployed=="pauschal":
                SalaryPerMonthEmp=(request.POST.get('SalaryPerMonthEmp'))
                DaysPerMonthMix=(request.POST.get("DaysPerMonthMix"))
                HoursPerDayMix=(request.POST.get("HoursPerDayMix"))
                JobPosition=(request.POST.get("JobPosition"))
                Experience=(request.POST.get("ExperienceEmplMix"))
                Happiness=(request.POST.get("Happiness"))
                comment=(request.POST.get("Message"))
                mediumobj = Medium(mediumname=MediumName, freeoremployed=FreeOrEmployed)
                mediumobj.save()
                print("Hey")
                d = mediumobj.datacollection_set.create(
                SalaryPerMonthEmp=int(SalaryPerMonthEmp),
                DaysPerMonthMix=int(DaysPerMonthMix),
                HoursPerDayMix=int(HoursPerDayMix),
                JobPosition=str(JobPosition),
                Experience=str(Experience),
                Happiness=int(Happiness),
                comment=str(comment),
                )


            if FreeOrEmployed=="frei":
                gehalt=(request.POST.get('lohnProAuftrag'))
                wohlfuehl=(request.POST.get("happiness"))



    return HttpResponseRedirect(reverse('honoradar:index'))
Beispiel #47
0
def managetoken(request, next_page):
    user = request.user
    logger.debug("user %s" % user)
    button = request.POST.get('button')
    if request.method == 'GET':
        context_dict = {
            't_vctoken': table_vctoken(user),
            'next_page': next_page,
        }
        return render(request, 'usertokens.html', context = context_dict)
    elif button == 'reset_notebook_token':
        return redirect('user:changetoken', next_page)
    elif button == 'reset_seaf_token':
        return redirect('user:changeseaftoken', next_page)
    elif button == 'apply':
        token_ids = request.POST.getlist('token_ids')
        for rm_token_id in request.POST.getlist('rm_token_ids'):
            try:
                token_ids.remove(rm_token_id)
                VCToken.objects.get(id = rm_token_id, user = user).delete()
                messages.info(request, "Deleted your token and related vcprojects")
                logger.debug("user %s deleted vctoken" % user)
            except Exception as e:
                logger.debug("user %s tried to delete vctoken id %s -- %s" % (user, rm_token_id, e))
        for new_repository_id in request.POST.getlist('new_repository_ids'):
            try:
                repository = VCRepository.objects.get(id = new_repository_id)
                fn_rsa = request.POST.get('fn_rsa-%s' % new_repository_id)
                token = request.POST.get('token-%s' % new_repository_id)
                un = request.POST.get('username-%s' % new_repository_id)
                assert len(fn_rsa), "The RSA filename cannot be empty"
                assert len(token), "Your token cannot be empty"
                vctoken = VCToken.objects.create(repository = repository, user = user, username = un, fn_rsa = fn_rsa, token = token)
                messages.info(request, "Your vctoken %s token is saved" % vctoken)
            except Exception as e:
                messages.error(request, "Cannot create your token -- %s" % e)
                logger.error("user %s cannot save vctoken" % (user))
        for tid in token_ids:
            try:
                fn_rsa_before = request.POST.get('fn_rsa_before-%s' % tid)
                token_before = request.POST.get('token_before-%s' % tid)
                un_before = request.POST.get('username_before-%s' % tid)
                fn_rsa = request.POST.get('fn_rsa_after-%s' % tid)
                token = request.POST.get('token_after-%s' % tid)
                un = request.POST.get('username_after-%s' % tid)
                assert len(fn_rsa), "The RSA filename cannot be empty"
                assert len(token), "Your token cannot be empty"
                if fn_rsa_before == fn_rsa and token_before == token and un_before == un:
                    continue
                vctoken = VCToken.objects.get(id = tid, user = user, username = un_before, fn_rsa = fn_rsa_before, token = token_before)
                vctoken.fn_rsa = fn_rsa
                vctoken.token = token
                vctoken.username = un
                vctoken.save()
                messages.info(request, "Your vctoken %s token is updated" % vctoken)
            except Exception as e:
                messages.error(request, "Cannot create your token -- %s" % e)
                logger.error("user %s cannot save vctoken" % (user))
        return redirect(next_page)
    else:
        messages.error(request, 'Abused call')
        return redirect(next_page)
Beispiel #48
0
def wall_post(request, graph):
    message = request.POST.get('message')
    if message:
        graph.set('me/feed', message=message)
        messages.info(request, 'Posted the message to your wall')
        return next_redirect(request)
Beispiel #49
0
 def post(self, request, *args, **kwargs):
     _, created = Token.objects.get_or_create(user=self.request.user)
     if created:
         messages.info(request, 'API Token created successfully')
     return HttpResponseRedirect(self.get_success_url())
Beispiel #50
0
def logout_request(request):
    logout(request)
    messages.info(request, "You have successfully logged out.")
    return redirect("API:index")
Beispiel #51
0
def handle_translate(obj, request, user_locked, this_unit_url, next_unit_url):
    '''
    Saves translation or suggestion to database and backend.
    '''
    # Antispam protection
    if not request.user.is_authenticated():
        antispam = AntispamForm(request.POST)
        if not antispam.is_valid():
            # Silently redirect to next entry
            return HttpResponseRedirect(next_unit_url)

    form = TranslationForm(request.POST)
    if not form.is_valid():
        return

    # Check whether translation is not outdated
    obj.check_sync()

    try:
        unit = Unit.objects.get_checksum(
            request,
            obj,
            form.cleaned_data['checksum'],
        )
    except Unit.DoesNotExist:
        return

    if 'suggest' in request.POST:
        # Handle suggesion saving
        user = request.user
        if form.cleaned_data['target'][0] == '':
            messages.error(request, _('Your suggestion is empty!'))
            # Stay on same entry
            return HttpResponseRedirect(this_unit_url)
        # Invite user to become translator if there is nobody else
        recent_changes = Change.objects.content().filter(
            translation=unit.translation, ).exclude(user=None)
        if not recent_changes.exists():
            messages.info(
                request,
                _('There is currently no active translator for this '
                  'translation, please consider becoming a translator '
                  'as your suggestion might otherwise remain unreviewed.'))
        # Create the suggestion
        unit.add_suggestion(
            join_plural(form.cleaned_data['target']),
            user,
        )
    elif not request.user.is_authenticated():
        # We accept translations only from authenticated
        messages.error(
            request, _('You need to log in to be able to save translations!'))
    elif not request.user.has_perm('trans.save_translation'):
        # Need privilege to save
        messages.error(request,
                       _('You don\'t have privileges to save translations!'))
    elif not user_locked:
        # Remember old checks
        oldchecks = set(unit.active_checks().values_list('check', flat=True))
        # Update unit and save it
        unit.target = join_plural(form.cleaned_data['target'])
        unit.fuzzy = form.cleaned_data['fuzzy']
        saved = unit.save_backend(request)

        if saved:
            # Get new set of checks
            newchecks = set(unit.active_checks().values_list('check',
                                                             flat=True))
            # Did we introduce any new failures?
            if newchecks > oldchecks:
                # Show message to user
                messages.error(
                    request, _('Some checks have failed on your translation!'))
                # Stay on same entry
                return HttpResponseRedirect(this_unit_url)

    # Redirect to next entry
    return HttpResponseRedirect(next_unit_url)
def logout_request(request):
    logout(request)
    messages.info(request, "logged out successfully")
    return redirect("main:homepage")
Beispiel #53
0
def receive_tip_v3(request, key, txid, network):
    """Handle the receiving of a tip (the POST).

    Returns:
        TemplateResponse: the UI with the tip confirmed.

    """
    these_tips = Tip.objects.filter(web3_type='v3', txid=txid, network=network)
    tips = these_tips.filter(metadata__reference_hash_for_receipient=key) | these_tips.filter(metadata__reference_hash_for_funder=key)
    tip = tips.first()
    if not tip:
        messages.error(request, 'This tip was not found')
        return redirect('/')
    if not request.user.is_authenticated or request.user.is_authenticated and not getattr(
        request.user, 'profile', None
    ):
        login_redirect = redirect('/login/github/?next=' + request.get_full_path())
        return login_redirect

    is_authed = request.user.username.lower() == tip.username.lower() or request.user.username.lower() == tip.from_username.lower() or not tip.username
    not_mined_yet = get_web3(tip.network).eth.getBalance(Web3.toChecksumAddress(tip.metadata['address'])) == 0
    did_fail = False
    if not_mined_yet:
        tip.update_tx_status()
        did_fail = tip.tx_status in ['dropped', 'unknown', 'na', 'error']

    num_redemptions = tip.metadata.get("num_redemptions", 0)
    max_redemptions = tip.metadata.get("max_redemptions", 0)
    is_redeemable = not (tip.receive_txid and (num_redemptions >= max_redemptions)) and is_authed
    has_this_user_redeemed = request.user.profile.tip_payouts.filter(tip=tip).count()
    if has_this_user_redeemed:
        is_redeemable = False
    if not is_redeemable:
        messages.info(request, 'This tip has been received already')
    elif not is_authed:
        messages.error(request, f'This tip is for @{tip.username} but you are logged in as @{request.user.username}.  Please logout and log back in as {tip.username}.')
    elif did_fail:
        messages.info(request, f'This tx {tip.txid}, failed.  Please contact the sender and ask them to send the tx again.')
    elif not_mined_yet:
        messages.info(request, f'This tx {tip.txid}, is still mining.  Please wait a moment before submitting the receive form.')
    elif request.POST.get('receive_txid') and is_redeemable:
        params = request.POST

        # db mutations
        try:
            profile = get_profile(tip.username)
            eth_address = params['forwarding_address']
            if not is_valid_eth_address(eth_address):
                eth_address = profile.preferred_payout_address
            if params['save_addr']:
                if profile:
                    profile.preferred_payout_address = eth_address
                    profile.save()
            tip.receive_txid = params['receive_txid']
            tip.receive_tx_status = 'pending'
            tip.receive_address = eth_address
            tip.received_on = timezone.now()
            num_redemptions = tip.metadata.get("num_redemptions", 0)
            # note to future self: to create a tip like this in the future set
            # tip.username
            # tip.metadata.max_redemptions
            # tip.metadata.override_send_amount
            # tip.amount to the amount you want to send
            # ,"override_send_amount":1,"max_redemptions":29

            num_redemptions += 1
            tip.metadata["num_redemptions"] = num_redemptions
            tip.save()
            record_user_action(tip.from_username, 'receive_tip', tip)
            record_tip_activity(tip, tip.username, 'receive_tip')
            TipPayout.objects.create(
                txid=tip.receive_txid,
                profile=request.user.profile,
                tip=tip,
                )
            messages.success(request, 'This tip has been received')
            is_redeemable = False
            has_this_user_redeemed = True
        except Exception as e:
            messages.error(request, str(e))
            logger.exception(e)

    gas_price_sanity_multiplier = 1.3
    params = {
        'issueURL': request.GET.get('source'),
        'class': 'receive',
        'title': _('Receive Tip'),
        'gas_price': round(float(gas_price_sanity_multiplier) * float(recommend_min_gas_price_to_confirm_in_time(1)), 1),
        'tip': tip,
        'has_this_user_redeemed': has_this_user_redeemed,
        'key': key,
        'is_redeemable': is_redeemable,
        'is_authed': is_authed,
        'disable_inputs': not is_redeemable or not is_authed,
    }

    return TemplateResponse(request, 'onepager/receive.html', params)
Beispiel #54
0
def translate(request, project, subproject, lang):
    '''
    Generic entry point for translating, suggesting and searching.
    '''
    obj = get_translation(request, project, subproject, lang)

    # Check locks
    project_locked, user_locked, own_lock = obj.is_locked(request, True)
    locked = project_locked or user_locked

    # Search results
    search_result = search(obj, request)

    # Handle redirects
    if isinstance(search_result, HttpResponse):
        return search_result

    # Get numer of results
    num_results = len(search_result['ids'])

    # Search offset
    try:
        offset = int(request.GET.get('offset', search_result.get('offset', 0)))
    except ValueError:
        offset = 0

    # Check boundaries
    if offset < 0 or offset >= num_results:
        messages.info(request, _('You have reached end of translating.'))
        # Delete search
        del request.session['search_%s' % search_result['search_id']]
        # Redirect to translation
        return HttpResponseRedirect(obj.get_absolute_url())

    # Some URLs we will most likely use
    base_unit_url = '%s?sid=%s&offset=' % (
        obj.get_translate_url(),
        search_result['search_id'],
    )
    this_unit_url = base_unit_url + str(offset)
    next_unit_url = base_unit_url + str(offset + 1)

    response = None

    # Any form submitted?
    if request.method == 'POST' and not project_locked:
        response = handle_translate(obj, request, user_locked, this_unit_url,
                                    next_unit_url)

    # Handle translation merging
    elif 'merge' in request.GET and not locked:
        response = handle_merge(obj, request, next_unit_url)

    # Handle accepting/deleting suggestions
    elif not locked and ('accept' in request.GET or 'delete' in request.GET):
        response = handle_suggestions(obj, request, this_unit_url)

    # Pass possible redirect further
    if response is not None:
        return response

    # Grab actual unit
    try:
        unit = obj.unit_set.get(pk=search_result['ids'][offset])
    except Unit.DoesNotExist:
        # Can happen when using SID for other translation
        messages.error(request, _('Invalid search string!'))
        return HttpResponseRedirect(obj.get_absolute_url())

    # Show secondary languages for logged in users
    if request.user.is_authenticated():
        profile = request.user.get_profile()
        secondary_langs = profile.secondary_languages.exclude(
            id=unit.translation.language.id)
        project = unit.translation.subproject.project
        secondary = Unit.objects.filter(
            checksum=unit.checksum,
            translated=True,
            translation__subproject__project=project,
            translation__language__in=secondary_langs,
        )
        # distinct('target') works with Django 1.4 so let's emulate that
        # based on presumption we won't get too many results
        targets = {}
        res = []
        for lang in secondary:
            if lang.target in targets:
                continue
            targets[lang.target] = 1
            res.append(lang)
        secondary = res
        antispam = None
    else:
        secondary = None
        antispam = AntispamForm()

    # Prepare form
    form = TranslationForm(
        initial={
            'checksum': unit.checksum,
            'target': (unit.translation.language, unit.get_target_plurals()),
            'fuzzy': unit.fuzzy,
        })
    search_form = SearchForm()

    return render_to_response(
        'translate.html',
        RequestContext(
            request,
            {
                'this_unit_url': this_unit_url,
                'first_unit_url': base_unit_url + '0',
                'last_unit_url': base_unit_url + str(num_results - 1),
                'next_unit_url': next_unit_url,
                'prev_unit_url': base_unit_url + str(offset - 1),
                'object': obj,
                'unit': unit,
                'last_changes': unit.change_set.all()[:10],
                'total': obj.unit_set.all().count(),
                'search_id': search_result['search_id'],
                'offset': offset,
                'filter_name': search_result['name'],
                'filter_count': num_results,
                'filter_pos': offset + 1,
                'form': form,
                'antispam': antispam,
                'comment_form': CommentForm(),
                'search_form': search_form,
                'update_lock': own_lock,
                'secondary': secondary,
                'locked': locked,
                'user_locked': user_locked,
                'project_locked': project_locked,
            },
        ))
Beispiel #55
0
 def form_valid(self, form):
     messages.info(self.request, '암호 변경을 완료했습니다.')
     return super().form_valid(form)
Beispiel #56
0
def view_profile(request, display_name):
    """View user profile."""
    user = get_object_or_404(User,
                             userprofile__display_name__iexact=display_name)
    user_is_alumni = user.groups.filter(name='Alumni').exists()
    if not user.groups.filter(Q(name='Rep') | Q(name='Alumni')).exists():
        raise Http404

    if (not user.userprofile.registration_complete
            and not request.user.has_perm('profiles.can_edit_profiles')):
        raise Http404

    nominee_form = forms.RotmNomineeForm(request.POST or None,
                                         instance=user.userprofile)

    usergroups = user.groups.filter(
        Q(name='Mentor')
        | Q(name='Council')
        | Q(name='Peers')
        | Q(name='Resources')
        | Q(name='Onboarding')
        | Q(name='Newsletter')
    )
    is_nomination_period = now().date() < rotm_nomination_end_date()
    data = {'pageuser': user,
            'user_profile': user.userprofile,
            'added_by': user.userprofile.added_by,
            'mentor': user.userprofile.mentor,
            'usergroups': usergroups,
            'user_nominated': user.userprofile.is_rotm_nominee,
            'is_nomination_period': is_nomination_period,
            'user_is_alumni': user_is_alumni}

    if UserStatus.objects.filter(user=user, is_unavailable=True).exists():
        status = UserStatus.objects.filter(user=user).latest('created_on')
        data['user_status'] = status
        if user == request.user:
            today = now().date()
            date = (status.expected_date.strftime('%d %B %Y')
                    if status.expected_date > today else None)
            msg = render_to_string(
                'includes/view_profile_unavailable_msg.jinja',
                {'date': date,
                 'display_name': user.userprofile.display_name})
            messages.info(request, mark_safe(msg))

    if nominee_form.is_valid():
        if ((is_nomination_period or waffle.switch_is_active('enable_rotm_tasks'))
                and request.user.groups.filter(name='Mentor').exists() and request.user != user):
            nominee_form.save(nominated_by=request.user)
            return redirect('profiles_view_profile', display_name=display_name)

        messages.warning(request, ('Only mentors can nominate a mentee.'))

    if user_is_alumni:
        msg = render_to_string('includes/alumni_msg.jinja')
        messages.info(request, mark_safe(msg))

    today = now().date()

    # NGReports
    data['ng_reports'] = (user.ng_reports
                          .filter(report_date__lte=today)
                          .order_by('-report_date'))

    past_user_events = get_events_for_user(user, to_date=today)

    data['future_events'] = get_events_for_user(user, from_date=today)
    data['past_events'] = past_user_events.reverse()[:10]
    data['featured_rep'] = user.featuredrep_users.all()
    data['request_user'] = request.user
    data['nominee_form'] = nominee_form

    return render(request, 'profiles_view.jinja', data)
Beispiel #57
0
def address_overview(request, coin_symbol, address, wallet_name=None):

    TXNS_PER_PAGE = 10

    if request.GET.get('page'):
        # get rid of old pagination (for googlebot)
        kwargs = {'coin_symbol': coin_symbol, 'address': address}
        return HttpResponseRedirect(reverse('address_overview', kwargs=kwargs))

    before_bh = request.GET.get('before')

    try:
        user_agent = request.META.get('HTTP_USER_AGENT')

        if is_bot(user_agent):
            # very crude hack!
            confirmations = 1
        else:
            confirmations = 0

        address_details = get_address_full(
                address=address,
                coin_symbol=coin_symbol,
                txn_limit=TXNS_PER_PAGE,
                inout_limit=5,
                confirmations=confirmations,
                api_key=BLOCKCYPHER_API_KEY,
                before_bh=before_bh,
                )
    except AssertionError:
        msg = _('Invalid Address')
        messages.warning(request, msg)
        redir_url = reverse('coin_overview', kwargs={'coin_symbol': coin_symbol})
        return HttpResponseRedirect(redir_url)

    # import pprint; pprint.pprint(address_details, width=1)

    if 'error' in address_details:
        msg = _('Sorry, that address was not found')
        messages.warning(request, msg)
        return HttpResponseRedirect(reverse('home'))

    if request.user.is_authenticated:
        # notify user on page of any forwarding or subscriptions they may have
        for address_subscription in AddressSubscription.objects.filter(
                auth_user=request.user,
                b58_address=address,
                coin_symbol=coin_symbol,
                unsubscribed_at=None,
                ):
            if address_subscription.auth_user.email_verified:
                msg = _('Private Message: you are subscribed to this address and will receive email notifications at <b>%(user_email)s</b> (<a href="%(unsub_url)s">unsubscribe</a>)' % {
                    'user_email': request.user.email,
                    'unsub_url': reverse('user_unsubscribe_address', kwargs={
                        'address_subscription_id': address_subscription.id,
                        }),
                    })
                messages.info(request, msg, extra_tags='safe')
            else:
                msg = _('Private Message: you are not subscribed to this address because you have not clicked the link sent to <b>%(user_email)s</b>' % {
                    'user_email': request.user.email,
                    })
                messages.error(request, msg, extra_tags='safe')
                print('ERROR')

        # there can be only one
        af_initial = get_object_or_None(AddressForwarding,
                auth_user=request.user,
                initial_address=address,
                coin_symbol=coin_symbol,
                )
        if af_initial:
            msg = _('''
            Private Message: this address will automatically forward to <a href="%(destination_addr_uri)s">%(destination_address)s</a>
            any time a payment is received.
            <br /><br /> <i>%(small_payments_msg)s</i>
            ''' % {
                'destination_address': af_initial.destination_address,
                'destination_addr_uri': reverse('address_overview', kwargs={
                    'address': af_initial.destination_address,
                    'coin_symbol': coin_symbol,
                    }),
                'small_payments_msg': SMALL_PAYMENTS_MSG,
                })
            messages.info(request, msg, extra_tags='safe')

        # There could be many
        for af_destination in AddressForwarding.objects.filter(
                auth_user=request.user,
                destination_address=address,
                coin_symbol=coin_symbol,
                ):
            msg = _('''
            Private Message: this address will automatically receive forwarded transactions from
            <a href="%(initial_addr_uri)s">%(initial_address)s</a>.
            <br /><br /> <i>%(small_payments_msg)s</i>
            ''' % {
                'initial_address': af_destination.initial_address,
                'initial_addr_uri': reverse('address_overview', kwargs={
                    'address': af_destination.initial_address,
                    'coin_symbol': coin_symbol,
                    }),
                'small_payments_msg': SMALL_PAYMENTS_MSG,
                })
            messages.info(request, msg, extra_tags='safe')

    all_transactions = address_details.get('txs', [])
    # import pprint; pprint.pprint(all_transactions, width=1)

    api_url = 'https://api.blockcypher.com/v1/%s/%s/addrs/%s/full?limit=50' % (
            COIN_SYMBOL_MAPPINGS[coin_symbol]['blockcypher_code'],
            COIN_SYMBOL_MAPPINGS[coin_symbol]['blockcypher_network'],
            address)

    return {
            'coin_symbol': coin_symbol,
            'address': address,
            'api_url': api_url,
            'wallet_name': wallet_name,
            'has_more': address_details.get('hasMore', False),
            'total_sent_satoshis': address_details['total_sent'],
            'total_received_satoshis': address_details['total_received'],
            'unconfirmed_balance_satoshis': address_details['unconfirmed_balance'],
            'confirmed_balance_satoshis': address_details['balance'],
            'total_balance_satoshis': address_details['final_balance'],
            'flattened_txs': all_transactions,
            'before_bh': before_bh,
            'num_confirmed_txns': address_details['n_tx'],
            'num_unconfirmed_txns': address_details['unconfirmed_n_tx'],
            'num_all_txns': address_details['final_n_tx'],
            'BLOCKCYPHER_PUBLIC_KEY': BLOCKCYPHER_PUBLIC_KEY,
            }
def logout(request):
    auth.logout(request)
    messages.info(request, "Cerraste sesión exitosamente", extra_tags="alert-info")
    return HttpResponseRedirect('/')
Beispiel #59
0
def setup_address_forwarding(request, coin_symbol):

    # kind of tricky because we have to deal with both logged in and new users
    already_authenticated = request.user.is_authenticated

    initial = {'coin_symbol': coin_symbol}

    if already_authenticated:
        form = KnownUserAddressForwardingForm(initial=initial)
    else:
        form = NewUserAddressForwardingForm(initial=initial)

    if request.method == 'POST':
        if already_authenticated:
            form = KnownUserAddressForwardingForm(data=request.POST)
        else:
            form = NewUserAddressForwardingForm(data=request.POST)

        if form.is_valid():
            coin_symbol = form.cleaned_data['coin_symbol']
            destination_address = form.cleaned_data['coin_address']
            user_email = form.cleaned_data.get('email')
            # optional. null in case of KnownUserAddressForwardingForm

            if already_authenticated:
                auth_user = request.user
            else:
                auth_user = None

                if user_email:
                    # Check for existing user with that email
                    existing_user = get_object_or_None(AuthUser, email=user_email)
                    if existing_user:
                        msg = _('Please first login to this account to create a notification')
                        messages.info(request, msg)
                        return HttpResponseRedirect(existing_user.get_login_uri())

                    else:
                        # Create user with unknown (random) password
                        auth_user = AuthUser.objects.create_user(
                                email=user_email,
                                password=None,  # it will create a random pw
                                creation_ip=get_client_ip(request),
                                creation_user_agent=get_user_agent(request),
                                )

                        # Login the user
                        # http://stackoverflow.com/a/3807891/1754586
                        auth_user.backend = 'django.contrib.auth.backends.ModelBackend'
                        login(request, auth_user)

                        # Log the login
                        LoggedLogin.record_login(request)
                else:
                    # No user email given, proceed anonymously
                    # FIXME: confirm this
                    pass

            # Setup Payment Forwarding
            forwarding_address_details = get_forwarding_address_details(
                    destination_address=destination_address,
                    api_key=BLOCKCYPHER_API_KEY,
                    callback_url=None,  # notifications happen separately (and not always)
                    coin_symbol=coin_symbol,
                    )

            if 'error' in forwarding_address_details:
                # Display error message back to user
                messages.warning(request, forwarding_address_details['error'], extra_tags='safe')

            else:

                initial_address = forwarding_address_details['input_address']

                # create forwarding object
                address_forwarding_obj = AddressForwarding.objects.create(
                        coin_symbol=coin_symbol,
                        initial_address=initial_address,
                        destination_address=destination_address,
                        auth_user=auth_user,
                        blockcypher_id=forwarding_address_details['id'],
                        )

                subscribe_uri = reverse('subscribe_address', kwargs={'coin_symbol': coin_symbol})
                uri_qs = {'a': initial_address}
                if user_email:
                    uri_qs['e'] = user_email
                if already_authenticated:
                    uri_qs['e'] = auth_user.email
                subscribe_uri = '%s?%s' % (subscribe_uri, urlencode(uri_qs))

                initial_addr_uri = reverse('address_overview', kwargs={
                    'coin_symbol': coin_symbol,
                    'address': initial_address,
                    })
                destination_addr_uri = reverse('address_overview', kwargs={
                    'coin_symbol': coin_symbol,
                    'address': destination_address,
                    })
                msg_merge_dict = {
                        'initial_address': initial_address,
                        'initial_addr_uri': initial_addr_uri,
                        'destination_address': destination_address,
                        'destination_addr_uri': destination_addr_uri,
                        'subscribe_uri': subscribe_uri,
                        'small_payments_msg': SMALL_PAYMENTS_MSG,
                        }
                if auth_user:
                    msg_merge_dict['user_email'] = auth_user.email

                if user_email or (already_authenticated and form.cleaned_data['wants_email_notification']):

                    # Create an address subscription for all of these cases

                    # Hit blockcypher and return subscription id
                    callback_uri = reverse('address_webhook', kwargs={
                        'secret_key': WEBHOOK_SECRET_KEY,
                        # hack for rare case of two webhooks requested on same address:
                        'ignored_key': simple_pw_generator(num_chars=10),
                        })
                    callback_url = uri_to_url(callback_uri)
                    bcy_id = subscribe_to_address_webhook(
                            subscription_address=initial_address,
                            callback_url=callback_url,
                            coin_symbol=coin_symbol,
                            api_key=BLOCKCYPHER_API_KEY,
                            )

                    # only notify for deposits
                    AddressSubscription.objects.create(
                            coin_symbol=coin_symbol,
                            b58_address=initial_address,
                            auth_user=auth_user,
                            blockcypher_id=bcy_id,
                            notify_on_deposit=True,
                            notify_on_withdrawal=False,
                            address_forwarding_obj=address_forwarding_obj,
                            )

                    if user_email:
                        # New signup
                        msg = _('''
                        Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
                        will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>,
                        but you must confirm your email to receive notifications.
                        <br /><br /> <i>%(small_payments_msg)s</i>
                        ''' % msg_merge_dict)
                        messages.success(request, msg, extra_tags='safe')

                        address_forwarding_obj.send_forwarding_welcome_email()
                        return HttpResponseRedirect(reverse('unconfirmed_email'))
                    else:
                        if auth_user.email_verified:

                            msg = _('''
                            Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
                            will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>,
                            and you will immediately receive an email notification at <b>%(user_email)s</b>.
                            <br /><br /> <i>%(small_payments_msg)s</i>
                            ''' % msg_merge_dict)
                            messages.success(request, msg, extra_tags='safe')

                            return HttpResponseRedirect(reverse('dashboard'))

                        else:
                            # existing unconfirmed user
                            msg = _('''
                            Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
                            will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>,
                            but you must confirm your email to receive notifications.
                            <br /><br /> <i>%(small_payments_msg)s</i>
                            ''' % msg_merge_dict)
                            messages.success(request, msg, extra_tags='safe')

                            address_forwarding_obj.send_forwarding_welcome_email()

                            return HttpResponseRedirect(reverse('unconfirmed_email'))

                elif already_authenticated:
                    # already authenticated and doesn't want subscriptions
                    msg = _('''
                    Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
                    will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>.
                    You will not receive email notifications (<a href="%(subscribe_uri)s">subscribe</a>).
                    <br /><br /> <i>%(small_payments_msg)s</i>
                    ''' % msg_merge_dict)
                    messages.success(request, msg, extra_tags='safe')

                    return HttpResponseRedirect(reverse('dashboard'))

                else:
                    # New signup sans email
                    msg = _('''
                    Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
                    will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>.
                    You will not receive email notifications (<a href="%(subscribe_uri)s">subscribe</a>).
                    <br /><br /> <i>%(small_payments_msg)s</i>
                    ''' % msg_merge_dict)
                    messages.success(request, msg, extra_tags='safe')

                    return HttpResponseRedirect(destination_addr_uri)

    elif request.method == 'GET':
        coin_address = request.GET.get('a')
        subscriber_email = request.GET.get('e')
        if coin_address:
            initial['coin_address'] = coin_address
        if subscriber_email and not already_authenticated:
            initial['email'] = subscriber_email
        if coin_address or subscriber_email:
            if already_authenticated:
                form = KnownUserAddressForwardingForm(initial=initial)
            else:
                form = NewUserAddressForwardingForm(initial=initial)

    return {
            'form': form,
            'coin_symbol': coin_symbol,
            'is_input_page': True,
            }
Beispiel #60
0
    def form_valid(self, form):
        """
        If the form is valid we, optionally, checkout the cart items
        and charge the invoiced items which are due now.
        """
        data = form.cleaned_data
        # We remember the card by default. ``processor_token_id`` is not present
        # when we are creating charges on a card already on file.
        if 'remember_card' in self.request.POST:
            # Workaround: Django does not take into account the value
            # of Field.initial anymore. Worse, it will defaults to False
            # when the field is not present in the POST.
            remember_card = data['remember_card']
        else:
            remember_card = form.fields['remember_card'].initial
        processor_token = data[self.processor_token_id]
        self.organization.update_address_if_empty(
            country=data.get('country'),
            region=data.get('region'),
            locality=data.get('card_city'),
            street_address=data.get('card_address_line1'),
            postal_code=data.get('card_address_zip'))

        # deep copy the invoicables because we are updating the list in place
        # and we don't want to keep the edited state on a card failure.
        self.sole_provider = None
        if not self.invoicables:
            LOGGER.error("No invoicables for user %s",
                         self.request.user,
                         extra={'request': self.request})
            messages.info(self.request,
              _("There are no items invoicable at this point. Please select an"\
" item before checking out."))
            return http.HttpResponseRedirect(reverse('saas_cart_plan_list'))
        invoicables = copy.deepcopy(self.invoicables)
        for invoicable in invoicables:
            # We use the following convention here:
            # POST parameters prefixed with cart- correspond to an entry
            # in the invoicables
            plan = invoicable['subscription'].plan
            plan_key = invoicable['name']
            if self.sole_provider is None:
                self.sole_provider = plan.organization
            elif self.sole_provider != plan.organization:
                self.sole_provider = False
            if plan_key in data:
                selected_line = int(data[plan_key]) - 1
                if (selected_line >= 0
                        and selected_line < len(invoicable['options'])):
                    line = invoicable['options'][selected_line]
                    # Normalize unlock line description to
                    # "subscribe <plan> until ..."
                    if match_unlock(line.descr):
                        nb_periods = plan.period_number(line.descr)
                        line.descr = describe_buy_periods(
                            plan,
                            plan.end_of_period(line.created_at, nb_periods),
                            nb_periods)
                    invoicable['lines'] += [line]

        try:
            self.charge = self.organization.checkout(
                invoicables,
                self.request.user,
                token=processor_token,
                remember_card=remember_card)
            if self.charge and self.charge.invoiced_total.amount > 0:
                messages.info(self.request, _("A receipt will be sent to"\
" %(email)s once the charge has been processed. Thank you.")
                          % {'email': self.organization.email})
        except ProcessorError as err:
            messages.error(self.request, err)
            return self.form_invalid(form)
        return super(CardInvoicablesFormMixin, self).form_valid(form)