Exemplo n.º 1
0
def create(request):
    if request.method == 'GET':
        context = { 'form': CreateForm() }
        return render(request, 'addrbook/create.html', context)

    entry = Entry(created_by=request.user, creation_time=datetime.now(),
                  updated_by=request.user, update_time=datetime.now())
    create_form = CreateForm(request.POST, request.FILES, instance=entry)
    if not create_form.is_valid():
        context = { 'form': create_form }
        return render(request, 'addrbook/create.html', context)
   
    # Save the new record (note: this sets value for entry.id)
    create_form.save()


    if create_form.cleaned_data['picture']:
        url = s3_upload(create_form.cleaned_data['picture'], entry.id)
        entry.picture_url = url
        entry.save()

    message = 'Entry created'
    edit_form = EditForm(instance=entry)
    context = { 'message': message, 'entry': entry, 'form': edit_form }
    return render(request, 'addrbook/edit.html', context)
Exemplo n.º 2
0
def edit(request, id):
    try:
        if request.method == 'GET':
            entry = Entry.objects.get(id=id)
            form = EditForm(instance=entry)
            context = { 'entry': entry, 'form': form }
            return render(request, 'addrbook/edit.html', context)
    
        entry = Entry.objects.select_for_update().get(id=id)
        db_update_time = entry.update_time  # Copy timestamp to check after form is bound
        form = EditForm(request.POST, request.FILES, instance=entry)
        if not form.is_valid():
            context = { 'entry': entry, 'form': form }
            return render(request, 'addrbook/edit.html', context)

        # if update times do not match, someone else updated DB record while were editing
        if db_update_time != form.cleaned_data['update_time']:
            # refetch from DB and try again.
            entry = Entry.objects.get(id=id)
            form = EditForm(instance=entry)
            context = {
                'message': 'Another user has modified this record.  Re-enter your changes.',
                'entry':   entry,
                'form':    form,
            }
            return render(request, 'addrbook/edit.html', context)

        if form.cleaned_data['picture']:
            url = s3_upload(form.cleaned_data['picture'], entry.id)
            entry.picture_url = url

        # Set update info to current time and user, and save it!
        entry.update_time = datetime.now()
        entry.updated_by  = request.user
        form.save()

        # form = EditForm(instance=entry)
        context = {
            'message': 'Entry updated.',
            'entry':   entry,
            'form':    form,
        }
        return render(request, 'addrbook/edit.html', context)
    except Entry.DoesNotExist:
        context = { 'message': 'Record with id={0} does not exist'.format(id) }
        return render(request, 'addrbook/search.html', context)