I\'m trying to make a model that\'s stores basic information about an Article also store the name of the currently logged in user, is this possible? or is it something that
You'll need to take care of this in the view:
# views.py
def create(request):
if request.POST:
form = ArticleForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return HttpResponseRedirect('/articles/all')
else:
form = ArticleForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_article.html', args)
# models.py
class Article(models.Model):
author = models.ForeignKey('auth.User')
You'll need to do it in the view, as the model has no idea where it is being created from. Pass commit=False
to the form.save()
method so it doesn't commit the data to the database, set the author from the request, and then save manually:
if form.is_valid():
article = form.save(commit=False)
article.author = request.user
article.save()
return HttpResponseRedirect('/articles/all')