Python django.shortcuts.get_object_or_404() Examples

The following are 30 code examples of django.shortcuts.get_object_or_404(). 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: views.py    From django-ajax-contacts with The Unlicense 8 votes vote down vote up
def contact_detail(request, pk):
    if request.method == 'POST':
        data = (request.POST.get(key) for key in ('name', 'fone', 'email'))
        contact = Contact.objects.get(pk=pk)
        contact.name, contact.fone, contact.email = data
        contact.save()
    else:
        contact = get_object_or_404(Contact, pk=pk)

    response = dict(
        name=contact.name,
        avatar=contact.avatar(),
        email=contact.email,
        phone=contact.fone,
        url=resolve_url('contact-details', pk=contact.pk)
    )
    return JsonResponse(response) 
Example #2
Source File: product.py    From Servo with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def download_products(request, group="all"):
    """
    Downloads entire product DB or just ones belonging to a group
    """
    filename = "products"
    data = u"ID\tCODE\tTITLE\tPURCHASE_PRICE\tSALES_PRICE\tSTOCKED\n"

    if group == "all":
        products = Product.objects.all()
    else:
        category = get_object_or_404(ProductCategory, slug=group)
        products = category.get_products()
        filename = group

    # @FIXME: Add total stocked amount to product
    # currently the last column is a placeholder for stock counts in inventory uploads
    for p in products:
        row = [unicode(i) for i in (p.pk, p.code, p.title, 
                                    p.price_purchase_stock,
                                    p.price_sales_stock, 0)]
        data += "\t".join(row) + "\n"

    return send_csv(data, filename) 
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: views.py    From django-classified with MIT License 7 votes vote down vote up
def get(self, request):
        area_slug = request.GET.get('area_slug')
        if area_slug:
            area = get_object_or_404(Area, slug=area_slug)
            area.set_for_request(request)
        else:
            Area.delete_for_request(request)

        next_url = self.request.GET.get('next') or reverse_lazy('django_classified:index')

        return redirect(next_url) 
Example #5
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def remove_product(request, pk, item_id):
    order = get_object_or_404(Order, pk=pk)

    # The following is to help those who hit Back after removing a product
    try:
        item = ServiceOrderItem.objects.get(pk=item_id)
    except ServiceOrderItem.DoesNotExist:
        messages.error(request, _("Order item does not exist"))
        return redirect(order)

    if request.method == 'POST':
        msg = order.remove_product(item, request.user)
        messages.info(request, msg)
        return redirect(order)

    return render(request, 'orders/remove_product.html', locals()) 
Example #6
Source File: customer.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def view(request, pk, group='all'):
    c = get_object_or_404(Customer, pk=pk)
    data = prepare_view(request, group)

    data['title'] = c.name
    data['orders'] = Order.objects.filter(
        customer__lft__gte=c.lft,
        customer__rght__lte=c.rght,
        customer__tree_id=c.tree_id
    )

    if c.email:
        data['notes'] = Note.objects.filter(recipient=c.email)

    data['customer'] = c
    request.session['return_to'] = request.path

    return render(request, 'customers/view.html', data) 
Example #7
Source File: purchases.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def create_po(request, product_id=None, order_id=None):
    """
    Creates a new Purchase Order
    """
    po = PurchaseOrder(created_by=request.user)
    po.location = request.user.get_location()
    po.save()

    if order_id is not None:
        po.sales_order = get_object_or_404(Order, pk=order_id)
        po.save()
        for i in ServiceOrderItem.objects.filter(order_id=order_id):
            po.add_product(i, amount=1, user=request.user)

    if product_id is not None:
        product = get_object_or_404(Product, pk=product_id)
        po.add_product(product, amount=1, user=request.user)

    messages.success(request, _("Purchase Order %d created" % po.pk))

    return redirect(edit_po, po.pk) 
Example #8
Source File: note.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def copy(request, pk):
    """Copy a note with its attachments and labels."""
    note = get_object_or_404(Note, pk=pk)

    new_note = Note(created_by=request.user)
    new_note.body = note.body
    new_note.order = note.order
    new_note.subject = note.subject
    new_note.save()

    new_note.labels = note.labels.all()

    for a in note.attachments.all():  # also copy the attachments
        a.pk = None
        a.content_object = new_note
        a.save()
        new_note.attachments.add(a)

    return redirect(edit, pk=new_note.pk, order_id=note.order_id) 
Example #9
Source File: note.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def delete_note(request, pk):
    """
    Deletes a note
    """
    note = get_object_or_404(Note, pk=pk)

    if request.method == 'POST':
        note.delete()
        messages.success(request, _("Note deleted"))

        if request.session.get('return_to'):
            url = request.session.get('return_to')
            del(request.session['return_to'])
        elif note.order_id:
            url = note.order.get_absolute_url()

        return redirect(url)

    return render(request, 'notes/remove.html', {'note': note}) 
Example #10
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 #11
Source File: note.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def toggle_flag(request, kind, pk, flag):
    """
    Toggles a flag of a note (read/unread, flagged/not, reported/not)
    """
    if kind == 'articles':
        note = get_object_or_404(Article, pk=pk)
        if flag == 'flagged':
            note.toggle_flagged(request.user)
            return HttpResponse(note.get_flagged_title(request.user))
        if flag == 'read':
            note.toggle_read(request.user)
            return HttpResponse(note.get_read_title(request.user))

    field = 'is_%s' % flag
    note = get_object_or_404(Note, pk=pk)
    attr = getattr(note, field)
    setattr(note, field, not attr)
    note.save()

    return HttpResponse(getattr(note, 'get_%s_title' % flag)()) 
Example #12
Source File: note.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def view_note(request, kind, pk):
    data = prep_list_view(request, kind)

    if kind == 'articles':
        note = get_object_or_404(Article, pk=pk)
        data['read_title'] = note.get_read_title(request.user)
        data['flagged_title'] = note.get_flagged_title(request.user)
    else:
        note = get_object_or_404(Note, pk=pk)

    data['title'] = note.get_title()
    data['note'] = note

    if kind == 'escalations':
        return render(request, "notes/view_escalation.html", data)

    if kind == 'articles':
        return render(request, "notes/view_article.html", data)

    return render(request, "notes/view_note.html", data) 
Example #13
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def update_gsx_details(request, pk):
    """
    Updates devices GSX warranty details
    """
    device = get_object_or_404(Device, pk=pk)
    try:
        GsxAccount.default(request.user)
        device.update_gsx_details()
        messages.success(request, _("Warranty status updated successfully"))
    except Exception as e:
        messages.error(request, e)

    if request.session.get('return_to'):
        return redirect(request.session['return_to'])

    return redirect(device) 
Example #14
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 #15
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 #16
Source File: gsx.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def add_part(request, repair, part):
    """
    Adds this part to this GSX repair
    """
    rep = get_object_or_404(Repair, pk=repair)
    soi = rep.order.serviceorderitem_set.get(pk=part)

    if request.method == "POST":
        try:
            part = rep.add_part(soi, request.user)
            data = {'part': part.part_number, 'repair': rep.confirmation}
            msg = _("Part %(part)s added to repair %(repair)s") % data
            messages.success(request, msg)
        except gsxws.GsxError, e:
            messages.error(request, e)

        return redirect(rep.order) 
Example #17
Source File: gsx.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def remove_part(request, repair, part):
    rep = get_object_or_404(Repair, pk=repair)
    part = get_object_or_404(ServicePart, pk=part)

    if request.method == "POST":

        rep.connect_gsx(request.user)
        gsx_rep = rep.get_gsx_repair()
        orderline = part.get_repair_order_line()
        orderline.toDelete = True
        orderline.orderLineNumber = part.line_number

        try:
            gsx_rep.update({'orderLines': [orderline]})
            data = {'part': part.code, 'repair': rep.confirmation}
            msg = _(u"Part %(part)s removed from %(repair)s") % data
            messages.success(request, msg)
        except gsxws.GsxError, e:
            messages.error(request, e)

        return redirect(rep.order) 
Example #18
Source File: gsx.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def delete_repair(request, pk):
    """Delete this unsubmitted GSX repair."""
    repair = get_object_or_404(Repair, pk=pk)

    if repair.is_submitted():
        messages.error(request, _('Submitted repairs cannot be deleted'))
        return redirect(repair.order)

    if request.method == 'POST':
        order = repair.order
        repair.delete()
        messages.success(request, _('GSX repair deleted'))
        return redirect(order)

    context = {'action': request.path}
    return render(request, 'repairs/delete_repair.html', context) 
Example #19
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def remove_user(request, pk, user_id):
    """
    Removes this user from the follower list, unsets assignee
    """
    order = get_object_or_404(Order, pk=pk)
    user  = get_object_or_404(User, pk=user_id)

    try:
        order.remove_follower(user)
        if user == order.user:
            order.set_user(None, request.user)
        msg = _('User %s removed from followers') % user
        order.notify("unset_user", msg, request.user)
    except Exception as e:
        messages.error(request, e)

    return redirect(order) 
Example #20
Source File: gsx.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def return_label(request, repair, part):
    """
    Returns the return label PDF for this repair and part
    """
    repair = get_object_or_404(Repair, pk=repair)

    try:
        repair.connect_gsx(request.user)
        label_data = repair.get_return_label(part)
        return HttpResponse(label_data, content_type="application/pdf")
    except gsxws.GsxError as e:
        messages.error(request, e)
        return redirect(repair.order) 
Example #21
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def edit_product(request, pk, item_id):
    """Edit a product added to an order."""
    order = Order.objects.get(pk=pk)
    item = get_object_or_404(ServiceOrderItem, pk=item_id)

    if not item.kbb_sn and item.product.part_type == "REPLACEMENT":
        try:
            device = order.devices.all()[0]
            item.kbb_sn = device.sn
        except IndexError:
            pass  # Probably no device in the order

    if item.product.component_code:
        try:
            GsxAccount.default(request.user, order.queue)
        except Exception as e:
            return render(request, "snippets/error_modal.html", {'error': e})

    form = OrderItemForm(instance=item)

    if request.method == "POST":
        form = OrderItemForm(request.POST, instance=item)
        if form.is_valid():
            try:
                item = form.save()
                # Set whoever set the KBB sn as the one who replaced the part
                if item.kbb_sn and not item.replaced_by:
                    item.replaced_by = request.user
                    item.save()

                messages.success(request, _(u"Product %s saved") % item.code)

                return redirect(order)
            except Exception as e:
                messages.error(request, e)

    product = item.product
    title = product.code
    prices = json.dumps(item.product.get_price())

    return render(request, "orders/edit_product.html", locals()) 
Example #22
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def list_products(request, pk):
    order = get_object_or_404(Order, pk=pk)
    return render(request, "orders/list_products.html", locals()) 
Example #23
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def select_customer(request, pk, customer_id):
    """
    Selects a specific customer for this order
    """
    order = get_object_or_404(Order, pk=pk)
    order.customer_id = customer_id
    order.save()

    return redirect(order) 
Example #24
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def complete_repair(request, order_id, repair_id):
    """Mark this repair as complete in GSX."""
    repair = get_object_or_404(Repair, pk=repair_id)

    if request.method == 'POST':
        try:
            repair.close(request.user)
            msg = _(u"Repair %s marked complete.") % repair.confirmation
            messages.success(request, msg)
        except GsxError as e:
            messages.error(request, e)

        return redirect(repair.order)

    return render(request, 'orders/close_repair.html', locals()) 
Example #25
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def reserve_products(request, pk):
    order = get_object_or_404(Order, pk=pk)

    if request.method == 'POST':
        for p in order.products.all():
            p.reserve_product()

        msg = _(u"Products of order %s reserved") % order.code
        order.notify("products_reserved", msg, request.user)
        messages.info(request, msg)

        return redirect(order)

    return render(request, "orders/reserve_products.html", locals()) 
Example #26
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def add_device(request, pk, device_id=None, sn=None):
    """
    Add a device to a service order.

    Use device_id with existing devices or
    sn for new devices (which should have gone through GSX search)
    """
    order = get_object_or_404(Order, pk=pk)

    if device_id is not None:
        device = Device.objects.get(pk=device_id)

    if sn is not None:
        sn = sn.upper()
        # not using get() since SNs are not unique
        device = Device.objects.filter(sn=sn).first()

        if device is None:
            try:
                device = Device.from_gsx(sn)
                device.save()
            except Exception as e:
                messages.error(request, e)
                return redirect(order)

    try:
        event = order.add_device(device, request.user)
        messages.success(request, event)
    except Exception as e:
        messages.error(request, e)
        return redirect(order)

    if order.customer:
        order.customer.devices.add(device)

    return redirect(order) 
Example #27
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def put_on_paper(request, pk, kind="confirmation", fmt='html'):
    """
    'Print' was taken?
    """
    order = get_object_or_404(Order, pk=pk)
    data = order.get_print_dict(kind)
    template = order.get_print_template(kind)

    if fmt == 'pdf':
        fn = data.get('title') + '.pdf'
        view = PDFTemplateView(request=request, template_name=template,
                               filename=fn)
        return view.render_to_response(data)

    return render(request, template, data) 
Example #28
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def toggle_flagged(request, pk):
    order = get_object_or_404(Order, pk=pk)
    t = FlaggedItem(content_object=order, flagged_by=request.user)
    t.save() 
Example #29
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def toggle_follow(request, order_id):
    order = get_object_or_404(Order, pk=order_id)
    data = {'icon': "open", 'action': _("Follow")}

    if request.user in order.followed_by.all():
        order.followed_by.remove(request.user)
    else:
        order.followed_by.add(request.user)
        data = {'icon': "close", 'action': _("Unfollow")}

    if request.is_ajax():
        return render(request, "orders/toggle_follow.html", data)

    return redirect(order) 
Example #30
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def reopen_order(request, pk):
    """Open a closed order."""
    order = get_object_or_404(Order, pk=pk)
    msg = order.reopen(request.user)
    messages.success(request, msg)
    return redirect(order)