Invalid Post - Return to Same Form - django

First, I'm not using django forms which I know could handle this. I may rewrite the app to do that but I'm looking for a quicker solution for the short term.
Problem:
Users submit a form with invalid data. I'd like to point them back to the same page with an error message and populate repopulate all the data they've already provided.
It seems like you should be able to do this with render_to_response() but I'm not quite sure how. Do I just edit the request and pass it back into the render_to_response? Any concrete examples or links to examples would be greatly appreciated.

Related

Pass POST data to FormWizard

Is it possible to pass POST data to the first step of a FormWizard?
I've got quite a lot of data to pass in to the wizard so I don't want to use url kwargs but I can't seem to figure out how to POST to it.
Any ideas?
I've never tried it, but if it's a lot of data, I think I would go about this by saving the POST data into the session. This way you can leave it there until you need it. I found an example of this at the bottom of this post:
Inserting initial data into a SessionWizardView form field either from a URL pattern or post data?

Connecting two views in Django

I want to make sure that my visitors (not authenticated users), are unable to visit a particular view without coming directly from a "previous view". I've kind of had to manually create a form preview and confirmation state. It's the step between submission and preview, and preview and confirm I'd like to "secure".
form submission-view -> preview-view -> confirm-view.
Is there some way that I can create a unique hash, POST it, and check if it's correct, or somewhat generate a cookie, session — or anything else that feels clever?
I'm a Django beginner (programming beginner in general) and any snippets' or pointing me in a right direction would be very much appreciated!
Thanks.
There are at least two ways you can accomplish this that I can think of:
One would be to include a hidden field in your form or querystring value that contains your hash/unique that you want to pick up in the next view. If it's not there, or incorrect, redirect.
Another would be to check the referring url from the request.META to see if they've come from the view you want them to come in on first, and save a session value from the form submission to carry through the rest of the views. If it's not there, redirect. If the referring URL isn't what you expect, redirect.
Whether you use a cookie, session, querystring parameter or hidden form post, it's all doing the same thing - validating a value exists. Whatever method works best, is what makes the most sense for you as the developer and most likely maintainer of said app.

Django forms: submission with mixed requests (get and post)

for seo related reason in my project i have to trap certain search parameters within the url for the "beautiful url" thing.
The advanced search is composed by 7 parameters, 3 of which are location-related and are the ones interesting our seo consultant.
So, now i'm a bit confused. It's been a while since i started using django professionally, but never had to face an issue like this. Basically, the final url structure must be something like this:
/Italy/Lombardy/Milan/?price=100&miles=10&last_posted=2
and my urls.py is
'/(?P<country>\w+)/(?P<zone>\w+)/(?P<city>\w+)/$', SearchView.as_view()
now, what i'm not sure about is how should i specify my request in the form method to be able to use that exact url schema? POST or GET? And how can i compose the url for the "action" attribute dynamically while the user types? Is this even the correct solution? I'm really confused about it, any help would be really appreciated! Thanks!
you will have to change the action field of the form using script, yes. and set the method to GET, and include in the form only the fields appearing in the query string.

How to override/update information from POST when creating model

I have a view that handles a POST request and attempts to create a new object. However, I know that some of the POST'd data is invalid... But I want to fix it and go ahead and create the object.
The only way I can figure out to be able to 'fix' data in a ModelForm is to create a 'is_valid()' form. To do this, I can either create the form with the POST data, or I can create it with an already existing instance. Unfortunately, if I use the POST data, because some of it is invalid, the form won't validate and I am thus unable to get to the data in the form to fix it. If I create it with an already existing instance, this works, but when the form is displayed, any remaining errors are for whatever reason ignored (and thus don't show up on the web page.) I've tried a combination of creating the the Model form from the POST data and giving it an instance, but this doesn't seem to help. Additionally, I've tried modifying (a copy of) the POST data, fixing it, and then creating the ModelForm from the 'fixed' POST data. This sort of works, with the exception that I have some ImageFields in my form, and they seem to just be ignored.
Any help would be greatly appreciated. I have looked at every good page that I can find to no avail.
Perhaps there is a better way to do this? The problem I'm trying to solve is that I want to have a model that contains ImageFields. The first time I put up the form, the user needs to 'upload' images for each of the fields. However, if he doesn't update an image for one of the fields, I want the new form to come up with a Image upload button on the fields where images have not been uploaded, and just a text field with the image name for images that have been uploaded.
Edit 9/15/2010:
Ok, I think I can simplify all of the above question into this:
def testing( request ) :
test_form = UserProfileForm()
valid = test_form.is_valid()
return render( 'testing.tmpl', locals(), request )
When the above code is rendered, the 'valid' shows as False (as one might expect), but the 'test_form' renders without any errors. I've read through (if perhaps not understood?) the documentation on Models and ModelForms, and I see that most of the time a ModelForm (in my case: UserProfileForm) is created with a specified 'instance'. However, 1) I don't have an instance yet, 2) I would still expect the non-instance'd Form to display errors. I'm sure there is something I am missing. Please illuminate. :)
One more thing, which perhaps the answer to the above will answer anyway, but as far as I can tell, the is_valid() call is supposed to call the 'clean()' function I defined for the UserProfileForm. However, (not being a python guru) I placed 'raise ValidationError()' at the top of clean(), and when I run the code, no error is shown. Thoughts?
Update: I figured out the problem and the answer is below. Thanks!
You should have a look at how to clean form fields in django. You could either manipulate the data returned from the form there or make any kind of validation!
If your ImageFields are optional then you can still validate them (that they are otherwise correct).
Then it's a matter of adjusting your template to show either the uploaded file name or an file upload field depending on whether they've already uploaded one or not. Actually, it would probably be better to give them both fields in the first case. That's what the automatic admin does (the upload field is labeled "Change").
Well, after figuring out how to use the python debugger (pdb) and the fact that within emacs it kind of 'just works' (wow!?) I was able to find that my (empty) form was not bound. Googling bound forms pointed me to this page:
http://docs.djangoproject.com/en/dev/ref/forms/api/
RTFM'ing I find that I can pass an empty dictionary to my form and then everything starts to behave as I would expect. So, to summarize, there is a big difference between:
test_form = UserProfileForm()
and
test_form = UserProfileForm( {} )
The second version causes the rendering of the form to show all the errors (and to call 'clean()').
With risk of having this deleted by the moderator ;) Thank you to all those who commented and for your patience with a new django developer.

django - the best way to combine pagination with filtering and request.POST - like stackoverflow - ajax?

I want to combine pagination with filtering. Since I have a lot of filters I do not want to send them per GET request, since the URLs get really ugly.
Since django pagination uses GET request to pass the page parameters, I do not know how I can combine these two approaches.
Any idea?
Great add-on would be: How can I combine this approach with table sort? :-)
Edit:
Actually it should work like the pagination of stackoverflow - user questions. If a user clicks on a page number one is shown the correct page, without showing the get parameters in the url.
This is the url called.
https://stackoverflow.com/api/userquestions.html?page=2&pagesize=10&userId=237690&sort=Recent
But the url shown in the browser is neat and short.
Seems to be ajax. Anybody an idea how to implement this? :)
If the URL is not shown in the browser`s address bar, I do not care about whether it is beautiful or not.
Edit: The solution:
Make an ajax update with all filter parameters passed to the view. This should help you get started with implementing ajax for your site: link
Thus the GET parameters never show up in the address bar.
have you checked the paginate application for django?
it may help you a lot, use it all the time :D
http://code.google.com/p/django-pagination/
Have you considered django-tables2? It gives you django-admin style tables without you having to write the logic yourself.
maybe you can use the urs, something like:
http://oursite.com/something/filter1/filter2/3/
the doc -> http://docs.djangoproject.com/en/1.1/topics/http/urls/
I figured out two solutions:
Instead of using just hyperlinks use it inside a POST form, i dont have any example now but i remember have used that for REST functions in Ruby on rails
Save the query info in a session.
Hope this help.