Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8650073
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T13:43:34+00:00 2026-06-12T13:43:34+00:00

I’m using Django 1.4 with Python 2.7 on Ubuntu 12.04. I have a view

  • 0

I’m using Django 1.4 with Python 2.7 on Ubuntu 12.04.

I have a view that gets information from a form post. The first thing it does is tries to find the client information based on the information given in the form.

While testing I’m putting in bogus information and it seems to be OK with that. I’m expecting it to throw a DoesNotExist exception then I’m calling the original view to present the user with the form again. Can I not do that?

Here are the two views:

def input_new_client(request):
    """
    ..  function:: input_new_client()

        Add the client based on the addClientInfo form

        :param request: Django Request object
    """
    ## Create a logging object
    path = os.path.join(os.path.dirname(__file__), 'logs/')
    filename = '{0}inputNewClient.log'.format(path)
    logfile = open(filename, 'w')
    now = datetime.datetime.now()
    logfile.write('\n --------------------- {0}\n'.format(now))

    if (request.method == "POST"):
        tkz_ys_api_id = request.POST.get("tkz_ys_api_id")
        tkz_ys_trans_key = request.POST.get("tkz_ys_trans_key")

        ## Validate the YS authentication information
        try:
            clientInfo = ClientInfo.objects.get(tkz_api_id = tkz_ys_api_id, tkz_trans_key = tkz_ys_trans_key)
        except ClientInfo.DoesNotExist or ClientInfo.MultipleObjectsReturned:
            logfile.write('{0}\n\n'.format(tkz_ys_api_id))
            logfile.write('{0}\n\n'.format(tkz_ys_trans_key))
            logfile.write('{0}\n\n'.format(traceback.format_exc()))
            logfile.close()
            state = "Invalid YS Authentication!  Please try again."
            add_new_client(request, state)
        else:
            if (clientInfo.name != "Your Solutions"):
                state = "Invalid YS Authentication!  Please try again."
                add_new_client(request, state)

        ## Generate a Tokeniz API ID and Trans Key for the new client
        (tkz_api_id, tkz_trans_key) = generate_credentials()

        ## Create a new client
        new_client = ClientInfo(name = request.POST.get("tkz_client_name"),
                                tkz_api_id = tkz_api_id,
                                tkz_trans_key = tkz_trans_key,
                                default_gateway_id = request.POST.get("tkz_gateway")
                               )
        new_client.save()

        ## Validate the YS authentication information
        try:
            clientInfo = ClientInfo.objects.get(tkz_api_id = tkz_api_id, tkz_trans_key = tkz_trans_key)
            foriegn_key = clientInfo.id
        except ClientInfo.DoesNotExist or ClientInfo.MultipleObjectsReturned:
            output = "Invalid YS Authentication!  Please try again."
            logfile.write('\n{0}\n'.format(output))
            logfile.write('{0}\n\n'.format(traceback.format_exc()))
            logfile.close()

        ## Setup the new clients gateway information
        new_gateway_info = GatewayInfo(client = foriegn_key,
                                       api_id = request.POST.get("tkz_gateway_api_id"),
                                       trans_key = request.POST.get("tkz_gateway_trans_key"),
                                       gateway_id = request.POST.get("tkz_gateway"),
                                      )
        new_gateway_info.save()

        data = {}
        data.update(csrf(request))
        data.update({ 'tkz_api_id' : tkz_api_id })
        data.update({ 'tkz_trans_key' : tkz_trans_key })
        data.update({ 'client_name' : request.POST.get("tkz_client_name")})

    return render_to_response("updatedClientCredentials.html", data)

And the original view that presents the form:

def add_new_client(request, state = None):
    """
    ..  function:: add_new_client()

        Provide a form for entering new client information

        :param request: Django Request object
        :param state: A message representing the state of the addition of a client
    """
    ## Create a logging object
    path = os.path.join(os.path.dirname(__file__), 'logs/')
    filename = '{0}addNewClient.log'.format(path)
    logfile = open(filename, 'a')
    now = datetime.datetime.now()
    logfile.write('\n --------------------- {0}\n'.format(now))

    if (state is None):
        state = "Enter information for adding a new client to Tokeniz."

    try:
        form = AddClientInfo()
    except:
        output = "Handle Error: Cannot create a valid form"
        logfile.write('{0}\n'.format(output))
        logfile.write('{0}\n\n'.format(traceback.format_exc()))
        logfile.close()
        return HttpResponse(output)

    try:
        data = {}
        data.update(csrf(request))
        data.update({ 'form' : form })
        data.update({ 'state' : state })
    except:
        output = "Handle Error: Cannot generate CSRF token"
        logfile.write('{0}\n'.format(output))
        logfile.write('{0}\n\n'.format(traceback.format_exc()))
        logfile.close()
        return HttpResponse(output)

    logfile.close()
    return render_to_response("addNewClientInfo.html", data)

I expect that the clientInfo = ClientInfo.objects.get(tkz_api_id = tkz_ys_api_id, tkz_trans_key = tkz_ys_trans_key) request in input_new_client would throw a DoesNotExist exception (as I put in fake data to ensure this to be the case).

So, I was just going to call the add_new_client view from within the exception.

The problem is that the input_new_client gets all the way down to the new_client.save() line, which fails for obvious reasons.

Any thoughts?

EDIT1:

I’ve modified the input_new_client view to have the following exception statement:

if (request.method == "POST"):
    tkz_ys_api_id = request.POST.get("tkz_ys_api_id")
    tkz_ys_trans_key = request.POST.get("tkz_ys_trans_key")
    tkz_gateway_id = int(request.POST.get("tkz_gateway"))

    ## Validate the YS authentication information
    try:
        clientInfo = ClientInfo.objects.get(tkz_api_id = tkz_ys_api_id, tkz_trans_key = tkz_ys_trans_key)
    except (ClientInfo.DoesNotExist, ClientInfo.MultipleObjectsReturned):
        logfile.write('tkz_ys_api_id = {0}\n\n'.format(tkz_ys_api_id))
        logfile.write('tkz_ys_trans_key = {0}\n\n'.format(tkz_ys_trans_key))
        logfile.write('tkz_gateway_id = {0}\n\n'.format(tkz_gateway_id))
        logfile.write('{0}\n\n'.format(traceback.format_exc()))
        logfile.close()
        state = "Invalid YS Authentication!  Please try again."
        add_new_client(request, state)
    else:
        if (clientInfo.name != "Your Solutions"):
            state = "Invalid YS Authentication!  Please try again."
            add_new_client(request, state)

I know it gets into the exception – I can verify with log info and the traceback. However, it does not go on to add_new_client. It instead skips along ahead and tries to insert a new entry in the ClientInfo model with incorrect data.

Why is it skipping the call to add_new_client?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T13:43:35+00:00Added an answer on June 12, 2026 at 1:43 pm

    This line:

    except ClientInfo.DoesNotExist or ClientInfo.MultipleObjectsReturned:
    

    doesn’t do what you think it does. The or is evaluated first, so in effect (I think) this is just trying to catch an exception of type True, which of course is never raised. What you actually want is this:

    except (ClientInfo.DoesNotExist, ClientInfo.MultipleObjectsReturned):
    

    (note the parentheses).

    Also note that the bare except clause in your second snippet is a very bad idea: it will catch all exceptions, so if something goes wrong that you weren’t expecting, you’ll never know about it. Make sure you only catch the handling errors that your except clause knows how to deal with.

    Edit

    Ah, I see what you’re doing now – you’re trying to return a response to the user from inside the exception. Well, there’s nothing wrong with that specifically, except that you don’t actually send it back to the user: you just call add_new_client(), and don’t do anything with the HTTP response that’s sent back. You need to actually return it to the user from there:

    except (ClientInfo.DoesNotExist, ClientInfo.MultipleObjectsReturned):
        ... logging stuff ...
        state = "Invalid YS Authentication!  Please try again."
        return add_new_client(request, state)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a view passing on information from a database: def serve_article(request, id): served_article
I have a text area in my form which accepts all possible characters from
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have a French site that I want to parse, but am running into
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;
I have thousands of HTML files to process using Groovy/Java and I need to
I'm trying to create an if statement in PHP that prevents a single post

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.