I’m going through a django tutorial to create a wiki and I’m a little stumped on what’s happening in the view below. Specifically, this part:
if form.is_valid():
article = form.save(commit=False)
article.author = request.user
article.save()
msg = "Article saved successfully"
messages.success(request, msg, fail_silently=True)
return redirect(article)
Here are my questions:
- what is being instantiating when you write
article = form.save(commit=False)and what does the argument,(commit=False)mean? - Where does
request.usercome from and what does it do? - I could also use an explanation for
article.save() - where does
messages.successcome from?
Sorry for all the questions, but the tutorial is a little sparse on details :(.
Here’s the model:
class Article(models.Model):
"""Represents a wiki article"""
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=50, unique=True)
text = models.TextField(help_text="Formatted using ReST")
author = models.ForeignKey(User)
is_published = models.BooleanField(default=False, verbose_name="Publish?")
created_on = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
published = PublishedArticlesManager()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Article, self).save(*args, **kwargs)
@models.permalink
def get_absolute_url(self):
return ('wiki_article_detail', (), { 'slug': self.slug })
Here’s the full view:
@login_required
def add_article(request):
form = ArticleForm(request.POST or None)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user
article.save()
msg = "Article saved successfully"
messages.success(request, msg, fail_silently=True)
return redirect(article)
return render_to_response('wiki/article_form.html',
{ 'form': form },
context_instance=RequestContext(request))
form.save(commit=False)and what does the argument,(commit=False)mean?
Saving a modelform inserts/updates the data in the database and returns the model istance (in this case an article instance). A modelform maps a form to a model. However, sometimes you may want to add some extra stuff that does not come directly from the form. So, to prevent two updates, you do not commit to the database by specifying
commit=False, the changes will be made to the database when you do a .save() on instance, instead.request.usercome from and what does it do?request.userrefers to the currently logged in user (who is making this request).article.save()– inserts/updates the article fields to the database.messages.successcome from? messages framework is just for passing error/success/informative messages using cookies and sessions.