Python django.shortcuts.get_object_or_404() Examples

The following are 30 code examples for showing how to use django.shortcuts.get_object_or_404(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.shortcuts , or try the search function .

Example 1
Project: django-ajax-contacts   Author: cuducos   File: views.py    License: The Unlicense 7 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
Project: Servo   Author: fpsw   File: product.py    License: 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
Project: Servo   Author: fpsw   File: product.py    License: BSD 2-Clause "Simplified" License 6 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 4
Project: Servo   Author: fpsw   File: customer.py    License: 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 5
Project: Servo   Author: fpsw   File: customer.py    License: 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 6
Project: Servo   Author: fpsw   File: account.py    License: 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 7
Project: Servo   Author: fpsw   File: device.py    License: 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 8
Project: Servo   Author: fpsw   File: device.py    License: 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 9
Project: Servo   Author: fpsw   File: order.py    License: 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 10
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 6 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 11
Project: Servo   Author: fpsw   File: purchases.py    License: 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 12
Project: Servo   Author: fpsw   File: note.py    License: 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 13
Project: Servo   Author: fpsw   File: note.py    License: 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 14
Project: Servo   Author: fpsw   File: note.py    License: 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 15
Project: Servo   Author: fpsw   File: note.py    License: 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 16
Project: Servo   Author: fpsw   File: gsx.py    License: 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
Project: Servo   Author: fpsw   File: gsx.py    License: 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
Project: Servo   Author: fpsw   File: gsx.py    License: 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
Project: django-classified   Author: slyapustin   File: views.py    License: MIT License 5 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 20
Project: pinax-documents   Author: pinax   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        if "p" in request.GET:
            qs = self.model.objects.for_user(request.user)
            self.parent = get_object_or_404(qs, pk=request.GET["p"])
        else:
            self.parent = None
        return super().get(request, *args, **kwargs) 
Example 21
Project: pinax-documents   Author: pinax   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        if "f" in request.GET:
            qs = Folder.objects.for_user(request.user)
            self.folder = get_object_or_404(qs, pk=request.GET["f"])
        else:
            self.folder = None
        return super().get(request, *args, **kwargs) 
Example 22
Project: pythonjobs.ie   Author: kimeraapp   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_object(self, queryset=None):
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        return get_object_or_404(Job, pk=pk, status=1) 
Example 23
Project: Servo   Author: fpsw   File: product.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def view_product(request, pk=None, code=None, group=None):

    product = Product()
    inventory = Inventory.objects.none()

    try:
        product = get_object_or_404(Product, pk=pk)
        inventory = Inventory.objects.filter(product=product)
    except Product.DoesNotExist:
        product = cache.get(code)

    data = prep_list_view(request, group)

    data['product'] = product
    data['inventory'] = inventory
    data['title'] = '%s - %s' % (product.code, product.title)

    # Collect data for Sales/Purchases/Invoices tabs
    results_per_page = 50
    page = request.GET.get('page')

    sales = product.serviceorderitem_set.all().select_related('order')
    sales = sales.order_by('-id')
    data['sales'] = paginate(sales, page, results_per_page)

    purchases = product.purchaseorderitem_set.all().select_related('purchase_order')
    purchases = purchases.order_by('-id')
    data['purchases'] = paginate(purchases, page, results_per_page)

    invoices = product.invoiceitem_set.all().select_related('invoice')
    invoices = invoices.order_by('-id')
    data['invoices'] = paginate(invoices, page, results_per_page)

    return render(request, "products/view.html", data) 
Example 24
Project: Servo   Author: fpsw   File: product.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def edit_category(request, slug=None, parent_slug=None):

    form = CategoryForm()
    category = ProductCategory()

    if slug is not None:
        category = get_object_or_404(ProductCategory, slug=slug)
        form = CategoryForm(instance=category)

    if parent_slug is not None:
        parent = get_object_or_404(ProductCategory, slug=parent_slug)
        form = CategoryForm(initial={'parent': parent.pk})

    if request.method == "POST":
        form = CategoryForm(request.POST, instance=category)
        if form.is_valid():
            try:
                category = form.save()
            except IntegrityError:
                error = _(u'Category %s already exists') % category.title
                messages.error(request, error)
                return redirect(list_products)
            messages.success(request, _(u"Category %s saved") % category.title)
            return redirect(category)
        else:
            messages.error(request, form.errors)
            return redirect(list_products)

    return render(request, "products/category_form.html", locals()) 
Example 25
Project: Servo   Author: fpsw   File: product.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def delete_category(request, slug):

    category = get_object_or_404(ProductCategory, slug=slug)

    if request.method == "POST":
        category.delete()
        messages.success(request, _("Category deleted"))
        return redirect(list_products)

    data = {'category': category}
    data['action'] = request.path
    return render(request, 'products/delete_category.html', data) 
Example 26
Project: Servo   Author: fpsw   File: customer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def add_order(request, customer_id, order_id):
    order = get_object_or_404(Order, pk=order_id)
    customer = get_object_or_404(Customer, pk=customer_id)
    order.customer = customer
    order.save()

    for d in order.devices.all():
        customer.devices.add(d)

    customer.save()
    messages.success(request, _('Customer added'))
    return redirect(order) 
Example 27
Project: Servo   Author: fpsw   File: customer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def notes(request, pk, note_id=None):
    from servo.forms.note import NoteForm
    customer = get_object_or_404(Customer, pk=pk)
    form = NoteForm(initial={'recipient': customer.name})

    return render(request, "notes/form.html", {'form': form}) 
Example 28
Project: Servo   Author: fpsw   File: customer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def delete_group(request, group):
    group = get_object_or_404(CustomerGroup, slug=group)

    if request.method == "POST":
        group.delete()
        messages.success(request, _(u'%s deleted') % group.name)
        return redirect(index)

    return render(request, "customers/delete_group.html", locals()) 
Example 29
Project: Servo   Author: fpsw   File: customer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def delete(request, pk=None, group='all'):

    customer = get_object_or_404(Customer, pk=pk)

    if request.method == "POST":
        customer.delete()
        messages.success(request, _("Customer deleted"))
        return redirect(index, group=group)
    else:
        data = {'action': request.path, 'customer': customer}
        return render(request, "customers/remove.html", data) 
Example 30
Project: Servo   Author: fpsw   File: rules.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def edit_rule(request, pk=None):
    title = _('Rules')
    object_list = Rule.objects.all()

    if pk:
        rule = get_object_or_404(Rule, pk=pk)

    if request.method == 'POST':
        if pk:
            rule = Rule.objects.get(pk=pk)
        else:
            rule = Rule()

        rule.description = request.POST.get('description')
        #rule.match = request.POST.get('description')
        rule.save()

        rule.condition_set.all().delete()
        rule.action_set.all().delete()

        keys = request.POST.getlist('condition-key')
        values = request.POST.getlist('condition-value')

        for k, v in enumerate(keys):
            cond = Condition(rule=rule)
            cond.key = v
            cond.value = values[k]
            cond.save()

        keys = request.POST.getlist('action-key')
        values = request.POST.getlist('action-value')

        for k, v in enumerate(keys):
            action = Action(rule=rule)
            action.key = v
            action.value = values[k]
            action.save()

            
    return render(request, "rules/form.html", locals())