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: 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 #3
Source File: stats.py    From Servo with BSD 2-Clause "Simplified" License 7 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: views.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def index(request):
    """
        This renders the index page of the site.
    """
    site_hdr = get_hdr()

    template_data = {HEADER: site_hdr}

    return render(request, 'main.html', template_data) 
Example #19
Source File: views.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def ab_models(request):
    """
        This is the view of all of our agent-based models.
    """
    site_hdr = get_hdr()

    model_list = ABMModel.objects.order_by('mtype')
    template_data = {'models': model_list, HEADER: site_hdr}
    return render(request, 'abmodels.html', template_data) 
Example #20
Source File: views.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def run(request):
    """
        This runs the model that was picked.
    """
    env = None
    try:
        action = request.POST[ACTION]
    except KeyError:
        action = None

    session_id = int(request.session['session_id'])

    # Load entry_point
    model_name = request.POST[MODEL]
    model = ABMModel.objects.get(name=model_name)
    entry_point = model.module
    plot_type = model.plot_type
    importlib.import_module(entry_point[0:-4])

    questions = model.params.all()

    # Take actions on a running model
    if action:
        env = running_model(request, action, entry_point,
                            questions, session_id)
    # Run a model for the first time
    else:
        env = model_first_run(request, action, entry_point, questions,
                              session_id, plot_type)

    site_hdr = get_hdr()

    text_box, image_bytes = env.user.text_output, env.plot()
    image = base64.b64encode(image_bytes.getvalue()).decode()

    template_data = {HEADER: site_hdr, 'text0': text_box[0], 'image': image,
                     'text1': text_box[1], 'model': model}

    return render(request, 'run.html', template_data) 
Example #21
Source File: views.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def help_page(request):
    """
        This function renders our help page.
    """
    site_hdr = get_hdr()
    return render(request, 'help.html', {HEADER: site_hdr}) 
Example #22
Source File: views.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def about(request):
    """
        This function renders our about page.
    """
    site_hdr = get_hdr()
    return render(request, 'about.html', {HEADER: site_hdr}) 
Example #23
Source File: views.py    From wechatpy with MIT License 5 votes vote down vote up
def index(request):
    return render(request, "index.html") 
Example #24
Source File: views.py    From MPContribs with MIT License 5 votes vote down vote up
def notebooks(request, nb):
    return render(
        request, os.path.join("notebooks", os.environ["PORTAL_CNAME"], nb + ".html")
    ) 
Example #25
Source File: views.py    From MPContribs with MIT License 5 votes vote down vote up
def manual_qmc_record_submission(request):
    if request.method == "POST":
        mat_form = MaterialSubmissionForm(request.POST)

        if mat_form.is_valid():
            mat_form.save()
            return HttpResponseRedirect("/thanks/")
    else:
        mat_form = MaterialSubmissionForm()

    return render(request, "materialsubmissionform.html", {"form": mat_form}) 
Example #26
Source File: views.py    From django-ajax-contacts with The Unlicense 5 votes vote down vote up
def home(request):
    return render(request, 'core/base.html') 
Example #27
Source File: views.py    From bottle-yang-extractor-validator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def index(request):
    context = versions
    context['results'] = {}
    return render(request, 'main.html', context) 
Example #28
Source File: views.py    From bottle-yang-extractor-validator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def upload_draft(request):
    context = versions
    context['results'] = {}
    savedir = mkdtemp()

    for file in request.FILES.getlist('data'):
        filepath = os.path.join(savedir, file.name)
        with open(filepath, 'wb+') as f:
            for chunk in file.chunks():
                f.write(chunk)
        context['results'] = create_output(filepath)

    rmtree(savedir)
    return render(request, 'main.html', context) 
Example #29
Source File: views.py    From bottle-yang-extractor-validator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def upload_file(request):
    context = versions
    context['results'] = {}
    savedfiles = []
    savedir = mkdtemp()

    for file in request.FILES.getlist('data'):
        name, ext = os.path.splitext(file.name)

        if ext == ".yang":
            with open(os.path.join(savedir, file.name), 'wb+') as f:
                for chunk in file.chunks():
                    f.write(chunk)
            savedfiles.append(file.name)

        if ext == ".zip":
            zipfilename = os.path.join(savedir, file.name)
            with open(zipfilename, 'wb+') as f:
                for chunk in file.chunks():
                    f.write(chunk)
            zf = ZipFile(zipfilename, "r")
            zf.extractall(savedir)
            for filename in zf.namelist():
                savedfiles.append(filename)

    for file in savedfiles:
        file_name = file.split("@")[0].replace(".", "_")
        pyang_res, confdc_res, yanglint_res, yangdump_res = validate_yangfile(file, savedir)
        context['results'][file] = {"pyang_stderr": pyang_res['stderr'], "pyang_output": pyang_res['stdout'],
                                    "confdc_stderr": confdc_res['stderr'],
                                    "yanglint_stderr": yanglint_res['stderr'],
                                    "yangdump_stderr": yangdump_res['stderr'], "name_split": file_name}

    rmtree(savedir)

    return render(request, 'main.html', context) 
Example #30
Source File: views.py    From bottle-yang-extractor-validator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def validate_rfc_param(request):
    rfc = request.GET['number']
    url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(rfc)
    results = {}
    results['results'] = create_output(url)
    return render(request, 'result.html', results)