When to use messages or 404 in django - django

I have a doubt when using django.contrib.messages or showing a 404 page. In which case do I should use one or the another?
serial = get_object_or_404(SerialNumber, serial_number=sn)
or
try:
serial = SerialNumber.objects.get(serial_number=sn)
except SerialNumber.DoesNotExist
messages.add_message(request, messages.WARNING, 'no found!')
Thanks in advance!

Let's say you have some url like this:
/article/<pk>/
If a end-user calls /article/5/ and there is no article with ID 5, then you should not only return a message, that the searched term is not found, but also the proper HTTP status code, which is 404. Here you should use get_object_or_404.
If you want to display some additional information on the page for /article/4/ and there is article with ID 4, but this particular additional information is not there, then you should display the page for article with ID 4, return HTTP status code 200, which means OK, and display the message, that the additional information is not available.
The main difference is in my opinion the proper handling of the HTTP status codes, but I let others teach me, if I'm wrong.

In my opinion, the main difference between 404 error and Django messages framework is that the 404 is related to the server, and messages are related to your application.
In other words, if a user requires an url which does not exist (ie. /url/which/doesnt/exist/) then the server should send a 404. But if a user requires a feature of your application which can fail or which gives info or debug messages (/articles/feature_acting_on_article_db/), then you should use messages framework.
As you can see in documentation https://docs.djangoproject.com/en/1.7/ref/contrib/messages/, messages are used at application level. The definition of 404 error is given by: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5:
(...)This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.
To conclude, I would say that the proper way to handle a url like /article/5/ where there is no 5th article is to send a message, because /article/pk/ is a feature which selects and displays info of the pk'th article (and no article doesn't mean that the command failed), even if the user entered a url (but that's my point of view about this question).

A 404 page page should be displayed when the user is trying to access any resource that is not available on the server.
On the other hand django messaging is used when you want to let the user see your application related custom messages. for example when he deletes or updates an entry you can show him a delete/update successful message.

Related

Missing template errors with strange path shown

This is not ColdFusion specific, but the server is ColdFusion 10 on Windows Server.
About once a day I'll get a log file of a string of missingtemplate errors, and I can't figure out if this is a typo somewhere on my part, or a user doing something, or some sort of exploration exploit.
The most recent one from last night doesn't seem like it affects the user, as by following CGI.QUERY_STRING I can see they come to the home page, hit our login_action.cfm page to log in, get into the logged in area and then again following the CGI.QUERY_STRING I can see what pages they were on by the URL variables.
The missing template target page argument is always this:
TARGETPAGE /https:/secure.domain.com/index.cfm
Which shows this for path translated and script name
PATH_TRANSLATED D:\web\site\https:\secure.domain.com\index.cfm
SCRIPT_NAME /https:/secure.domain.com/index.cfm
After she logs in I can see by the CGI dump that she is indeed logged in OK
PATH_TRANSLATED D:\web\site\https:\secure.domain.com\user\login\index.cfm
Under the query_string I'll be able to see what pages she's on with ?p=home, ?p=editaccount (URL would be index.cfm?p=home etc.)
I don't believe this is malicious, nothing is exposed to the user as far as error reporting, but nonetheless I'd like to figure out why / how this happens about once per day on this application, and understand how it does not seem to effect the user on the site yet throws these missingtemplate errors.
You may have a malformed link somewhere in your app.
Look at the referrer of the error page, then inspect that previous page on the client side (as a user).
Also look at the user agent. It could be a browser trying to pre-fetch pages - and I'm assuming one is from a malformed link.

How to monitor an action by user on Glass

I have a mirror API based app in which i have assigned a custom menu item, clicking on which should insert a new card. I have a bit of problem in doing that. I need to know of ways i can debug this.
Check if the subscription to the glass timeline was successful.
Print out something on console on click of the menu.
Any other way i can detect whether on click of the menu, the callback URL was called or not.
It sounds like you have a problem, but aren't sure how to approach debugging it? A few things to look at and try:
Question 1 re: checking subscriptions
The object returned from the subscriptions.insert should indicate that the subscription is a success. Depending on your language, an exception or error would indicate a problem.
You can also call subscriptions.list to make sure the subscriptions are there and are set to the values you expect. If a user removes authorization for your Glassware, this list will be cleared out.
Some things to remember about the URL used for subscriptions:
It must be an HTTPS URL and cannot use a self-signed certificate
The address must be resolvable from the public internet. "localhost" and local name aliases won't work.
The machine must be accessible from the public internet. Machines with addresses like "192.168.1.10" probably won't be good enough.
Question 2 re: printing when clicked
You need to make sure the subscription is setup correctly and that you have a webapp listening at the address you specified that will handle POST operations at that URL. The method called when that URL is hit is up to you, of course, so you can add logging to it. Language specifics may help here.
Try testing it yourself by going to the URL you specify using your own browser. You should see the log message printed out, at a minimum.
If you want it printed for only the specific menu item, you will need to make sure you can decode the JSON body that is sent as part of the POST and respond based on the operation and id of the menu item.
You should also make sure you return HTTP code 200 as quickly as possible - if you don't, Google's servers may retry for a while or eventually give up if they never get a response.
Update: From the sample code you posted, I noticed that you're either logging at INFO or sending to stdout, which should log to INFO (see https://developers.google.com/appengine/docs/java/#Java_Logging). Are you getting the logging from the doGet() method? This StackOverflow question suggests that appengine doesn't display items logged at INFO unless you change the logging.properties file.
Question 3 re: was it clicked or not?
Depending on the configuration of your web server and app server, there should be logs about what URLs have been hit (as noted by #scarygami in the comments to your question).
You can test it yourself to make sure you can hit the URL and it is logging. Keep in mind, however, the warnings I mentioned above about what makes a valid URL for a Mirror API callback.
Update: From your comment below, it sounds like you are seeing the URL belonging to the TimelineUpdateServlet is being hit, but are not seeing any evidence that the log message in TimelineUpdateServlet.doPost() is being called. What return code is logged? Have you tried calling this URL manually via POST to make sure the URL is going to the servlet you expect?

HTTP status for different conflict scenarios

I'm implementing user registration for a Web Service.
When somebody wants to register an account, my WS sends an activation link to his/her mail. Until this link is clicked, user account is not activated (but the info is persisted in database, so the resource exists).
So my question is, if you try to register the same mail several times, you will get a 409 CONFLICT code. But there are two scenarios right there:
User account pending on confirmation
User already registered and activated
I would like to know what is the right approach. Should I "invent" an HTTP status 4XX to distinguish them, or send 409 with a JSON with info? other solutions?
Thx!
EDIT:
I have found this response -> https://stackoverflow.com/a/3290369/1171280 where Piskvor suggest to use 409 status and request header to explain the reason why it failed and/or body. Which one? header? body? both?
What do you think?
EDIT 2:
HTTP status + body with detailed error (with machine-parseable codes even) is OK, Twitter does that (https://dev.twitter.com/docs/error-codes-responses) and RESPECT :) . But I still doubt with 403 vs 409... :S
Pending account is a special type of a user account, so I think both accounts (already registered and pending) are same in the context of your question. You should return 409 in both cases. For the REST API both are same cases because that resource already exists in the system.
Regarding your updated question, I would suggest using body (JSON) to send out error(s) instead of using a custom HTTP header to explain the reason why the call failed. Reason is that in the body can you have multiple error messages (each one as a separate JSON object/array element) where as in the header you can have only one (though you can split based on some character). Other reason is that you can have one generic error handling method which looks for an "error" object in the JSON instead of looking for different custom headers for each failure scenario.
HTTP codes:
403 - The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be
repeated.
409 - The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in
situations where it is expected that the user might be able to resolve
the conflict and resubmit the request.
I think it should be 409 because the conflict can be resolved by re-issuing the request with different email address.
HTTP status codes are not meant to "invented".
409 CONFLICT sounds OK to me. Including details in the body ist OK, too, if your client needs to know.
Don't use 409. Use 403.
[409] is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request.
It's for a request that should have been OK, but has a problem that can be resolved. If you edit a document and PUT the revised text but someone else did the same thing before you did, you should have a chance to look at the other person's work so you don't accidentally undo all their work. You'd get a 409 which means, if you want to revise it, you should send your revision with an indication that you've seen the latest revision by the other person -- i.e. you know what you're doing.
There's no way to 'correct' a redundant attempt to register. The only way to avoid the conflict is to register with a different username, but that's very incorrect.
I'm imagining a POST request that takes a username and email address and creates a new resource dedicated to that new user (which should now be used for validation), sending that resource's URL in an email. So you're dealing with the refusal of the POST request handler to create a new resource, for a reason specific to the business model of your application (rather than an HTTP-related reason like bad syntax).
There's no status code more specific to what you want than 403. In this case, all you should use HTTP's vocabulary to communicate is 'that's not allowed' -- use the layer on top of HTTP to communicate why, like a polite HTML page or a JSON object for the client to understand and render as a polite HTML page.
409 should be ok; for the details https://datatracker.ietf.org/doc/html/draft-nottingham-http-problem-04 might be of interest.

OAuthException (#368) The action attempted has been deemed abusive or is otherwise disallowed

I'm trying to post a feed on my wall or on the wall on some of my friends using Graph API. I gave all permissions that this application needs, allow them when i make the request from my page, I'm having a valid access token but even though this exception occurs and no feed is posted. My post request looks pretty good, the permissions are given. What do I need to do to show on facebook app that I'm not an abusive person. The last think I did was to dig in my application Auth Dialog to set all permission I need there, and to write why do I need these permissions.
I would be very grateful if you tell me what is going on and point me into the right direction of what do I need to do to fix this problem.
Had the same problem. I figured out that Facebook was refusing my shortlinks, which makes me a bit mad...but I get the point because its possible that shortlinks can be used to promote malicious content...so if you have shortlinks as part of your test, replace them w the full url...
I believe this message is encountered for one of the two reasons :
Your post contains malicious links
You are trying to make a POST request over a non-https connection.
The second one is not confirmed but I have seen that behavior. While same code in my heroku hosted app worked fine, it gave this #368 error on my 000webhost hosted .tk domain which wasn't secured by SSL
Just in case anyone is still struggling with this, the problem occurs when you put URLs or "action links" that are not in your own app domain, if you really need to post to an extarnal page, you'll have to post to your app first, then redirect from there using a script or something. hope that helps.
also it's better in my opinion to use HTTPS links, as sometimes i've seen a behaviour where http links would be rejected, but that's intermittent.
I started noticing that recently as well when running my unit tests. One of the tests I run is submitting a link that I know Facebook has blocked to verify that I handle the error correctly. I used to get this error:
Warning: This Message Contains Blocked Content: Some content in this message has been reported as abusive by Facebook...
But starting on July 4th, I started receiving this error instead:
(#368) The action attempted has been deemed abusive or is otherwise disallowed'
Both errors indicate that Facebook doesn't like what you're publishing.

django-paypal PDT implementation can't receive signals

I am trying to implement django-paypal (dcramers version from git) using PDT with subscriptions.
It works fine (meaning that the return_url is requested and answered), however signals are not triggered (put in models.py). I am using the following signals, connected to two different functions.
from paypal.standard.pdt.signals import pdt_successful, pdt_failed
What I noticed while browsing through my access logs is that I do get a POST request from paypal which is turned down.
"POST /an-obscure-string/pdt/ HTTP/1.0" 401 401 "-" "-"
I tried to modify /paypal/standard/pdt/views.py to accept POST requests but I still get the 401 error. I think this is the reason signals are not triggered.
I am having a bad time with this. Any help would be greatly appreciated.
PS: I am using the sandbox account
EDIT These are my PAYPAL POSTBACK values from conf.py
POSTBACK_ENDPOINT = "https://www.paypal.com/cgi-bin/webscr"
SANDBOX_POSTBACK_ENDPOINT = "https://www.sandbox.paypal.com/cgi-bin/webscr"
You are right, that is the reason why the signal does not get called since signals are sent at the very end of the view if the model's verify succeed.
Your solution is indeed wrong, Paypal will definitely send a GET request with the transaction ID to your app url if you choosed to use PDN.
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_html_paymentdatatransfer
I really suggest you to check your settings (on paypal account) since you are probably using IPN which uses POST requests.
Another possible cause of this is that after you received the GET request from paypal your app sends the POST data to your app instead of to paypal postback endpoint. (https://github.com/johnboxall/django-paypal/blob/master/standard/pdt/models.py#L47)
I would look at the access logs to see if the POST request comes after a GET request (for the same url), if yes I would check the value of the SANDBOX_POSTBACK_ENDPOINT and POSTBACK_ENDPOINT settings.