Python django.shortcuts.render() Examples

The following are 30 code examples of django.shortcuts.render(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.shortcuts , or try the search function .
Example #1
Source File: product.py    From Servo with BSD 2-Clause "Simplified" License 8 votes vote down vote up
def choose_product(request, order_id, product_id=None, target_url="orders-add_product"):
    """
    order_id can be either Service Order or Purchase Order
    """
    data = {'order': order_id}
    data['action'] = request.path
    data['target_url'] = target_url

    if request.method == "POST":
        query = request.POST.get('q')

        if len(query) > 2:
            products = Product.objects.filter(
                Q(code__icontains=query) | Q(title__icontains=query)
            )
            data['products'] = products

        return render(request, 'products/choose-list.html', data)

    return render(request, 'products/choose.html', data) 
Example #2
Source File: stats.py    From Servo with BSD 2-Clause "Simplified" License 8 votes vote down vote up
def devices(request):
    data = prep_view(request)
    data['form'] = DeviceStatsForm()
    start_date = data['initial']['start_date']
    end_date = data['initial']['end_date']

    if request.method == 'POST':
        form = DeviceStatsForm(request.POST)
        if form.is_valid():
            start_date = form.cleaned_data['start_date']
            end_date = form.cleaned_data['end_date']

    cursor  = connection.cursor()
    query = '''SELECT d.description device, count(o) AS orders, count(r) AS repairs 
        FROM servo_device d, servo_order o, servo_repair r, servo_orderdevice od 
        WHERE d.id = od.device_id 
            AND o.id = od.order_id 
            AND r.order_id = o.id
            AND (o.created_at, o.created_at) OVERLAPS (%s, %s)
        GROUP BY d.description''';
    cursor.execute(query, [start_date, end_date])
    data['results'] = cursor.fetchall()
    data['title'] = _('Device statistics')

    return render(request, "stats/devices.html", data) 
Example #3
Source File: product.py    From Servo with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def delete_product(request, pk, group):
    from django.db.models import ProtectedError
    product = get_object_or_404(Product, pk=pk)

    if request.method == 'POST':
        try:
            product.delete()
            Inventory.objects.filter(product=product).delete()
            messages.success(request, _("Product deleted"))
        except ProtectedError:
            messages.error(request, _('Cannot delete product'))

        return redirect(list_products, group)

    action = request.path
    return render(request, 'products/remove.html', locals()) 
Example #4
Source File: stats.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def index(request):
    """
    /stats/
    """
    data = prep_view(request)
    form = TechieStatsForm(initial=data['initial'])

    if request.method == 'POST':
        form = TechieStatsForm(request.POST, initial=data['initial'])
        if form.is_valid():
            request.session['stats_filter'] = form.serialize()

    data['form'] = form
    return render(request, "stats/index.html", data)


#@cache_page(15*60) 
Example #5
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def edit_calendar(request, pk=None, view="week"):
    from servo.models.calendar import CalendarForm
    calendar = Calendar(user=request.user)

    if pk:
        calendar = get_object_or_404(Calendar, pk=pk)
        if not calendar.user == request.user:
            messages.error(request, _('You can only edit your own calendar'))
            return redirect(calendars)

    if request.method == "POST":
        form = CalendarForm(request.POST, instance=calendar)

        if form.is_valid():
            calendar = form.save()
            messages.success(request, _("Calendar saved"))
            return redirect(view_calendar, calendar.pk, 'week')

    form = CalendarForm(instance=calendar)

    data = {'title': calendar.title}
    data['form'] = form
    data['action'] = request.path

    return render(request, "accounts/calendar_form.html", data) 
Example #6
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def register(request):
    """
    New user applying for access
    """
    form = RegistrationForm()
    data = {'title': _("Register")}

    if request.method == 'POST':

        form = RegistrationForm(request.POST)

        if form.is_valid():
            user = User(is_active=False)
            user.email = form.cleaned_data['email']
            user.last_name = form.cleaned_data['last_name']
            user.first_name = form.cleaned_data['first_name']
            user.set_password(form.cleaned_data['password'])
            user.save()

            messages.success(request, _(u'Your registration is now pending approval.'))

            return redirect(login)

    data['form'] = form
    return render(request, 'accounts/register.html', data) 
Example #7
Source File: product.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def upload_gsx_parts(request, group=None):
    from servo.forms.product import PartsImportForm
    form = PartsImportForm()

    data = {'action': request.path}

    if request.method == "POST":

        form = PartsImportForm(request.POST, request.FILES)

        if form.is_valid():
            data = form.cleaned_data
            filename = "servo/uploads/products/partsdb.csv"
            destination = open(filename, "wb+")

            for chunk in data['partsdb'].chunks():
                destination.write(chunk)

            messages.success(request, _("Parts database uploaded for processing"))
            return redirect(list_products)

    data['form'] = form
    return render(request, "products/upload_gsx_parts.html", data) 
Example #8
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def delete_calendar(request, pk):
    calendar = get_object_or_404(Calendar, pk=pk)

    if calendar.user != request.user:
        messages.error(request, _("Users can only delete their own calendars!"))

        return redirect(calendars)

    if request.method == "POST":
        calendar.delete()
        messages.success(request, _('Calendar deleted'))
        return redirect(calendars)

    data = {'title': _("Really delete this calendar?")}
    data['action'] = request.path

    return render(request, "accounts/delete_calendar.html", data) 
Example #9
Source File: checkin.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def find_device(request):
    device = Device(sn=request.GET['sn'])
    device.description = _('Other Device')
    device_form = forms.DeviceForm(instance=device)

    try:
        apple_sn_validator(device.sn)
    except Exception as e:  # not an Apple serial number
        return render(request, "checkin/device_form.html", locals())

    try:
        device = get_device(request, device.sn)
        device_form = forms.DeviceForm(instance=device)
    except GsxError as e:
        error = e

    return render(request, "checkin/device_form.html", locals()) 
Example #10
Source File: customer.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def edit_group(request, group='all'):
    if group == 'all':
        group = CustomerGroup()
    else:
        group = CustomerGroup.objects.get(slug=group)

    title = group.name
    form = GroupForm(instance=group)

    if request.method == "POST":
        form = GroupForm(request.POST, instance=group)
        if form.is_valid():
            group = form.save()
            messages.success(request, _(u'%s saved') % group.name)
            return redirect(index, group.slug)
        messages.error(request, form.errors['name'][0])
        return redirect(index)

    return render(request, "customers/edit_group.html", locals()) 
Example #11
Source File: checkin.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def status(request):
    """Check service order status through the checkin."""
    title = _('Repair Status')

    if request.GET.get('code'):
        timeline = []
        form = forms.StatusCheckForm(request.GET)
        if form.is_valid():
            code = form.cleaned_data['code']
            try:
                order = Order.objects.get(code=code)
                status_description = order.get_status_description()
                if Configuration.conf('checkin_timeline'):
                    timeline = order.orderstatus_set.all()
                if order.status is None:
                    order.status_name = _(u'Waiting to be processed')
            except Order.DoesNotExist:
                messages.error(request, _(u'Order %s not found') % code)
            return render(request, "checkin/status-show.html", locals())
    else:
        form = forms.StatusCheckForm()

    return render(request, "checkin/status.html", locals()) 
Example #12
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def delete_device(request, product_line, model, pk):
    dev = get_object_or_404(Device, pk=pk)

    if request.method == 'POST':
        from django.db.models import ProtectedError
        try:
            dev.delete()
            messages.success(request, _("Device deleted"))
        except ProtectedError:
            messages.error(request, _("Cannot delete device with GSX repairs"))
            return redirect(dev)

        return redirect(index)

    data = {'action': request.path}
    data['device'] = dev

    return render(request, "devices/remove.html", data) 
Example #13
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def accessories(request, pk, device_id):
    from django.utils import safestring

    if request.POST.get('name'):
        a = Accessory(name=request.POST['name'])
        a.order_id = pk
        a.device_id = device_id
        a.save()

    choice_list = []
    choices = Accessory.objects.distinct('name')

    for c in choices:
        choice_list.append(c.name)

    action = reverse('orders-accessories', args=[pk, device_id])
    selected = Accessory.objects.filter(order_id=pk, device_id=device_id)
    choices_json = safestring.mark_safe(json.dumps(choice_list))

    return render(request, 'devices/accessories_edit.html', locals()) 
Example #14
Source File: views.py    From MPContribs with MIT License 6 votes vote down vote up
def contribution(request, cid):
    ctx = get_context(request)
    client = Client(headers=get_consumer(request))  # sets/returns global variable
    contrib = client.contributions.get_entry(
        pk=cid, _fields=["id", "identifier"]
    ).result()
    ctx["identifier"], ctx["cid"] = contrib["identifier"], contrib["id"]
    nb = client.notebooks.get_entry(pk=cid).result()  # generate notebook with cells
    ctx["ncells"] = len(nb["cells"])

    if not nb["cells"][-1]["outputs"]:
        try:
            nb = client.notebooks.get_entry(pk=cid).result(
                timeout=1
            )  # trigger cell execution
        except HTTPTimeoutError as e:
            dots = '<span class="loader__dot">.</span><span class="loader__dot">.</span><span class="loader__dot">.</span>'
            ctx["alert"] = f"Detail page is building in the background {dots}"

    ctx["nb"], ctx["js"] = export_notebook(nb, cid)
    return render(request, "contribution.html", ctx.flatten()) 
Example #15
Source File: views.py    From MPContribs with MIT License 6 votes vote down vote up
def index(request):
    ctx = get_context(request)
    cname = os.environ["PORTAL_CNAME"]
    template_dir = get_app_template_dirs("templates/notebooks")[0]
    htmls = os.path.join(template_dir, cname, "*.html")
    ctx["notebooks"] = [
        p.split("/" + cname + "/")[-1].replace(".html", "") for p in glob(htmls)
    ]
    ctx["PORTAL_CNAME"] = cname
    ctx["landing_pages"] = []
    mask = ["project", "title", "authors", "is_public", "description", "urls"]
    client = Client(headers=get_consumer(request))  # sets/returns global variable
    entries = client.projects.get_entries(_fields=mask).result()["data"]
    for entry in entries:
        authors = entry["authors"].strip().split(",", 1)
        if len(authors) > 1:
            authors[1] = authors[1].strip()
        entry["authors"] = authors
        entry["description"] = entry["description"].split(".", 1)[0] + "."
        ctx["landing_pages"].append(
            entry
        )  # visibility governed by is_public flag and X-Consumer-Groups header
    return render(request, "home.html", ctx.flatten()) 
Example #16
Source File: customer.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def move(request, pk, new_parent=None):
    """
    Moves a customer under another customer
    """
    customer = get_object_or_404(Customer, pk=pk)

    if new_parent is not None:
        if int(new_parent) == 0:
            new_parent = None
            msg = _(u"Customer %s moved to top level") % customer
        else:
            new_parent = Customer.objects.get(pk=new_parent)
            d = {'customer': customer, 'target': new_parent}
            msg = _(u"Customer %(customer)s moved to %(target)s") % d

        try:
            customer.move_to(new_parent)
            customer.save() # To update fullname
            messages.success(request, msg)
        except Exception as e:
            messages.error(request, e)

        return redirect(customer)

    return render(request, "customers/move.html", locals()) 
Example #17
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def close(request, pk):
    """Close this Service Order."""
    order = get_object_or_404(Order, pk=pk)

    if request.method == 'POST':
        try:
            order.close(request.user)
        except Exception as e:
            messages.error(request, e)
            return redirect(order)

        if request.session.get("current_order_id"):
            del(request.session['current_order_id'])
            del(request.session['current_order_code'])
            del(request.session['current_order_customer'])

        messages.success(request, _('Order %s closed') % order.code)

        return redirect(order)

    data = {'order': order, 'action': reverse(close, args=[pk])}
    return render(request, "orders/close.html", data) 
Example #18
Source File: stats.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def statuses(request):
    data = prep_view(request)
    form = StatusStatsForm(initial=data['initial'])
    if request.method == 'POST':
        form = StatusStatsForm(request.POST, initial=data['initial'])
        if form.is_valid():
            # Store the name of the status since we don't have
            # IDs in events, yet
            status = form.cleaned_data['status'].title
            f = form.serialize()
            f['status'] = status
            request.session['stats_filter'] = f

    data['form'] = form
    return render(request, "stats/statuses.html", data) 
Example #19
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def search_gsx_repairs(request, pk):
    """
    Performs async GSX search for this device's GSX repairs
    """
    device = get_object_or_404(Device, pk=pk)

    try:
        GsxAccount.default(request.user)
        results = {'results': device.get_gsx_repairs()}
        return render(request, "devices/search_gsx_repairs.html", results)
    except gsxws.GsxError as message:
        return render(request, "search/results/gsx_error.html", locals()) 
Example #20
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_info(request, pk):
    device = get_object_or_404(Device, pk=pk)
    return render(request, "devices/get_info.html", locals()) 
Example #21
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def choose(request, order_id):
    """
    Choosing a device from within an SRO
    Does GSX lookup in case device is not found locally
    """
    context = {'order': order_id}

    if request.method == "POST":

        query = request.POST.get('q').upper()
        results = Device.objects.filter(Q(sn__iexact=query) | Q(imei=query))

        if len(results) < 1:
            try:
                current_order = request.session.get("current_order_id")
                current_order = Order.objects.get(pk=current_order)
                if current_order and current_order.queue:
                    GsxAccount.default(request.user, current_order.queue)
                else:
                    GsxAccount.default(request.user)
                    results = [Device.from_gsx(query)]
            except Exception as e:
                context['error'] = e
                return render(request, "devices/choose-error.html", context)

        context['results'] = results
        return render(request, "devices/choose-list.html", context)

    return render(request, "devices/choose.html", context) 
Example #22
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def stats(request):
    from servo.views.stats import prep_view, BasicStatsForm
    data = prep_view(request)
    form = BasicStatsForm(initial=data['initial'])
    if request.method == 'POST':
        form = BasicStatsForm(request.POST, initial=data['initial'])
        if form.is_valid():
            request.session['stats_filter'] = form.cleaned_data
    data['form'] = form
    return render(request, "accounts/stats.html", data) 
Example #23
Source File: stats.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def sales(request):
    data = prep_view(request)
    form = InvoiceStatsForm(initial=data['initial'])

    if request.method == 'POST':
        form = InvoiceStatsForm(request.POST, initial=data['initial'])
        if form.is_valid():
            request.session['stats_filter'] = form.serialize()

    data['form'] = form
    return render(request, "stats/sales.html", data) 
Example #24
Source File: stats.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def queues(request):
    data = prep_view(request)
    form = OrderStatsForm(initial=data['initial'])
    if request.method == 'POST':
        form = OrderStatsForm(request.POST, initial=data['initial'])
        if form.is_valid():
            request.session['stats_filter'] = form.serialize()

    data['form'] = form
    return render(request, "stats/queues.html", data) 
Example #25
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def print_calendar(request, pk, view, start_date):
    data = prepare_calendar_view(request, pk, view, start_date)
    calendar = data['calendar']

    data['location'] = request.user.location
    # Don't show unfinished events in the report
    data['events'] = data['events'].exclude(finished_at=None)
    data['subtitle'] = calendar.subtitle(data['start'], data['finish'])
    return render(request, "accounts/print_calendar.html", data) 
Example #26
Source File: error.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def report(request):
    crashed = True
    if request.method == 'POST':
        form = ErrorForm(request.POST)
        if form.is_valid():
            ref = 'Error %s' % from_time()
            recipient = settings.ADMINS[0][1]
            send_mail(ref, form.cleaned_data['description'], request.user.email, [recipient])
            crashed = False
    else:
        initial = _('Browser: %s') % request.META['HTTP_USER_AGENT']
        form = ErrorForm(initial={'description': initial})

    return render(request, 'error.html', locals()) 
Example #27
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def calendars(request):
    data = {'title': _('Calendars')}
    data['calendars'] = Calendar.objects.filter(user=request.user)

    if data['calendars'].count() > 0:
        cal = data['calendars'][0]
        return redirect(view_calendar, cal.pk)

    return render(request, "accounts/calendars.html", data) 
Example #28
Source File: diagnostics.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def select_test(request, pk):
    """
    Fetch test suite selector
    """
    error = None
    device = get_object_or_404(Device, pk=pk)

    try:
        tests = device.fetch_tests(request)
    except Exception as e:
        error = e

    return render(request, "diagnostics/select_test.html", locals()) 
Example #29
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def logout(request):
    if request.method == 'POST':
        auth.logout(request)
        messages.info(request, _("You have logged out"))

        return redirect(login)

    return render(request, "accounts/logout.html") 
Example #30
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def orders(request):
    """
    This is basically like orders/index, but limited to the user
    First, filter by the provided search criteria,
    then check if we have a saved search filter
    then default to user id
    Always update saved search filter
    """
    args = request.GET.copy()
    default = {'state': Order.STATE_OPEN}

    if len(args) < 2:
        f = request.session.get("account_search_filter", default)
        args = QueryDict('', mutable=True)
        args.update(f)

    # On the profile page, filter by the user, no matter what
    args.update({'followed_by': request.user.pk})
    request.session['account_search_filter'] = args

    data = prepare_list_view(request, args)
    data['title'] = _("My Orders")

    del(data['form'].fields['assigned_to'])

    return render(request, "accounts/orders.html", data)