Django for Designers/CRUD: Difference between revisions

Redirect after post
imported>Paulproteus
(→‎CRUD with asynchronous Javascript: More comma dict stuff)
imported>Paulproteus
(Redirect after post)
Line 94:
Spin up http://localhost:8000/, login if you're not logged in already, take a look at your beautiful new form!
 
Right now, if you try to submit bookmarks with this form, it'll just reload the page. That's because we haven't told the view to do anything with any form data that gets sent to it! Let's edit ''views.py''. andFirst, changelet's justadd thean ''index'' functionimport to makethe ittop do(keeping somethingthe withexisting this form'simports datathere):
 
<source lang="python">
from django.shortcuts import redirect
</source>
 
Then, let's change just the ''index'' function to make it do something with this form's data:
 
<source lang="python">
Line 102 ⟶ 108:
if form.is_valid():
form.save()
return redirect(index)
bookmarks = Bookmark.objects.all().order_by('-timestamp')[:10]
form = BookmarkForm()
Line 111 ⟶ 118:
</source>
 
What's going on here? We first check to see if the request method was a POST (as opposed to a GET, the usual method your browser uses when you're just reading a web page). If so, we use our ModelForm class to make an instance of the ModelForm using the data that we received via the POST from the HTML form's fields. If the form's built-in validator functions come back clean, we save the ModelForm, which makes a shiny new Bookmark in our database! Once we have made the change, we do a redirect back to the home page. (This avoids a common problem; read more on [http://en.wikipedia.org/wiki/Post/Redirect/Get Wikipedia].)
 
Save your work, then try making some new bookmarks via your new form. The page should reload, with your new bookmark at the top of the list! High five!
Line 121 ⟶ 128:
So our form works, but it doesn't look the way we originally expected. For one, there's a dropdown asking us to specify the bookmark's author. For another, we're missing a field for tags. We'll need to customize our BookmarkForm if we want it to look the way we want.
 
First, let's make the default author always be the currently logged-in user. Edit just the ''index'' function in ''views.py'':
 
<source lang="python">
Anonymous user