Ejemplo n.º 1
0
def login_page(request):
    form = LoginForm(request.POST or None)
    context = {"form": form}
    redirect_path = 'deskfriend-home'
    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            if is_safe_url(redirect_path, request.get_host()):
                messages.success(request, f'Your login is successful')
                return redirect(redirect_path)
            else:
                messages.failure(
                    request,
                    f'Your login is unsuccessful, check if you entered your email and password correctly'
                )
                return redirect("/")
        else:
            messages.success(
                request,
                f'Your login is unsuccessful, check if you entered your email and password correctly.'
            )
    return render(request, "accounts/login.html", context)
Ejemplo n.º 2
0
def comment_add(request, class_id, subject, id):
    if (not class_id or not subject or not id):
        return HttpResponseForbidden()

    else:
        try:
            information = {}
            information['student'] = Student.objects.get(nric__exact=id)
            form = CommentForm(request.POST)
            if form.is_valid():
                comment = form.save(commit=False)
                comment.student = information['student']
                staff = StaffProfile.objects.get(user__exact=request.user)
                staffname = staff.firstname + ' ' + staff.lastname
                comment.commentBy = staffname
                comment.commentDate = datetime.datetime.now().date()
                comment.commentTime = datetime.datetime.now().strftime(
                    "%H:%M:%S")
                form.save()
                messages.success(
                    request,
                    f'Comment for student has been submitted successfully!')
                return redirect('performance-home')

        except ObjectDoesNotExist:
            print("No entries found for comment_add!")
            messages.failure(request,
                             f'Something went wrong when trying to comment!')
            return redirect('performance-home')

    return render(request, 'student_settings/performance_add.html', {
        'active_page': 'student',
        'information': information,
        'form': form
    })
Ejemplo n.º 3
0
def donate(request):
    if request.method == 'POST':
        form = forms.DonateForm(request.POST)
        if form.is_valid():
            with xact.xact():
                stripe.api_key = STRIPE_PRIVATE_KEY
                token = request.POST['stripeToken']
                try:
                    charge = stripe.Charge.create(
                        amount=int(form.cleaned_data['amount']) *
                        100,  # amount needs to be in cents
                        currency="usd",
                        card=token,
                        description=form.cleaned_data['email'])

                    school = form.cleaned_data['school']
                    if school.id is None:
                        # this could just set country_code and then school.save(), but that
                        # creates a race condition for two users creating same school at
                        # same time, resulting in IntegrityError
                        school, created = model.School.objects.get_or_create(
                            name=school.name,
                            postcode=school.postcode,
                            defaults={
                                'country_code':
                                form.cleaned_data['country_code'],
                                'auto': school.auto,
                            },
                        )

                    donation = model.Donation(
                        name=form.cleaned_data['name'],
                        email=form.cleaned_data['email'],
                        phone=form.cleaned_data['phone'],
                        country_code=form.cleaned_data['country_code'],
                        school=school,
                        amount=int(form.cleaned_data['amount']) * 100,
                        charge_data=json.dumps(charge),
                        # We could add a currency field if donating in CAD is necessary
                    )
                    donation.save()

                except stripe.AuthenticationError:
                    # The stripe key was incorrect
                    messages.failure(
                        request,
                        u"Sorry, there was an issue with the payment.")
                except stripe.CardError, e:
                    # The card has been declined
                    messages.failure(
                        request,
                        u"Sorry, there was an issue with the payment.")

            messages.success(request, u"Payment accepted!")
            return redirect(redirect_home(request.user))
Ejemplo n.º 4
0
def subscribe(request):
    site = get_current_site(request)
    if (request.method == 'POST' and site.siteconfig.mailchimp_username and
            site.siteconfig.mailchimp_api_key and
            site.siteconfig.mailchimp_list_id):
        form = SubscribeForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            client = MailChimp(
                         site.siteconfig.mailchimp_username,
                         site.siteconfig.mailchimp_api_key
                     )

            try:
                client.lists.members.get(
                    site.siteconfig.mailchimp_list_id,
                    cd['email']
                )
            except requests.exceptions.HTTPError as e:
                if e.response.status_code == 404:
                    client.lists.members.create(
                        site.siteconfig.mailchimp_list_id,
                        {
                            'email_address': cd['email'],
                            'status': 'pending',
                            'merge_fields': {
                                'FNAME': cd['fname']
                            },
                        }
                    )
                    messages.success(
                        request,
                        'Thanks, you have been subscribed to our list!'
                    )
                else:
                    messages.failure(
                        request,
                        'Something went wrong, please try again'
                    )
            else:
                messages.warning(
                    request,
                    'Looks like this address is already subscribed to '
                    'our list!'
                )
        else:
            messages.warning(
                request,
                'There was a problem with the form, please try again'
            )

    return HttpResponseRedirect(reverse('jobs_index'))
Ejemplo n.º 5
0
def donate(request):
    if request.method == 'POST':
        form = forms.DonateForm(request.POST)
        if form.is_valid():
            with xact.xact():
                stripe.api_key = STRIPE_PRIVATE_KEY
                token = request.POST['stripeToken']
                try:
                    charge = stripe.Charge.create(
                        amount=int(form.cleaned_data['amount'])*100, # amount needs to be in cents
                        currency="usd",
                        card=token,
                        description=form.cleaned_data['email']
                    )

                    school = form.cleaned_data['school']
                    if school.id is None:
                        # this could just set country_code and then school.save(), but that
                        # creates a race condition for two users creating same school at
                        # same time, resulting in IntegrityError
                        school, created = model.School.objects.get_or_create(
                            name=school.name,
                            postcode=school.postcode,
                            defaults={
                                'country_code': form.cleaned_data['country_code'],
                                'auto': school.auto,
                                },
                            )

                    donation = model.Donation(
                        name=form.cleaned_data['name'],
                        email=form.cleaned_data['email'],
                        phone=form.cleaned_data['phone'],
                        country_code=form.cleaned_data['country_code'],
                        school=school,
                        amount = int(form.cleaned_data['amount'])*100,
                        charge_data = json.dumps(charge),
                        # We could add a currency field if donating in CAD is necessary
                    )
                    donation.save()

                except stripe.AuthenticationError:
                    # The stripe key was incorrect
                    messages.failure(request, u"Sorry, there was an issue with the payment.")
                except stripe.CardError, e:
                    # The card has been declined
                    messages.failure(request, u"Sorry, there was an issue with the payment.")

            messages.success(request, u"Payment accepted!")
            return redirect(redirect_home(request.user))
Ejemplo n.º 6
0
def register(request):
    if request.method == "POST":
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(
                request,
                'Your Account Has Been Created,Kindly Login With Your Credential'
            )
            return redirect('login')
        else:
            messages.failure(request, f'Something went wrong try again ')
            return redirect('register')

    form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})
Ejemplo n.º 7
0
 def post(self, request, pk=1):
     form = NoteForm(request.POST)
     if form.is_valid():
         profile = get_profile(request.user)
         data = form.cleaned_data
         try:
             note = Note()
             note.startup = Startup.objects.get(pk=pk)
             note.owner = profile
             note.text = data["text"].encode("utf8")
             note.save()
             messages.success(request, 'Note added.')
         except Exception as e:
             messages.failure(request, 'Failed: %s' % e) 
             
         return redirect('radar_access:startup_detail', pk)
     else:
         return self.get(request, pk=pk, note_form=form)
Ejemplo n.º 8
0
def contact_index(request):

    # Create objects for context

    # Retrieve contact points (social media, github, etc.)
    contact_points = ContactPoint.objects.order_by('n_page_order')
    # Create empty form
    contact_form = ContactForm()

    if request.method == 'POST':
        contact_form = ContactForm(request.POST)
        if contact_form.is_valid():
            # Get value of input from spam check field
            spam_check = contact_form.cleaned_data['spam_check']

            # Check spam check input
            if not spam_check:
                # Create email contents
                # Get the person's name
                name = contact_form.cleaned_data['name']
                # Create the email subject using their name
                subject = 'New message from ' + name
                # Get the person's message
                message = contact_form.cleaned_data['message']

                # Before emailing, write message to DB so that it is not lost if the email fails
                contact_message = ContactMessage(t_name=name,
                                                 t_message=message)
                # Save the message to the DB
                contact_message.save()
                # Try sending the email
                try:
                    # Send email using send_mail function
                    send_mail(subject,
                              message,
                              settings.EMAIL_HOST_USER,
                              ['*****@*****.**'],
                              fail_silently=False)
                    # Add code here for success message
                    messages.success(request, 'Message sent!')
                    return HttpResponseRedirect('/contact/')
                except BadHeaderError:
                    # Add code here for failure message
                    messages.failure(request, 'Uhh, what are you doing?')
                    return HttpResponseRedirect('/contact/')
                except Exception as e:
                    print(e)
                    # Display this anyway - we at least stored the message
                    # Could add code to email admin that message was saved, but not emailed
                    messages.success(request, 'Your message was sent!')
                    return HttpResponseRedirect('/contact/')
            else:
                messages.success(request, 'Message sent! ;)')
                return HttpResponseRedirect('/contact/')
        else:
            return HttpResponseRedirect('/contact/')
    # Anything but a POST request
    else:
        # Create context
        context = {
            'contact_points': contact_points,
            'contact_form': contact_form,
        }

    # Return request with context
    return render(request, 'contact_index.html', context)