livingcobble
livingcobble

Reputation: 11

how to fill an author field with current username

I have looked at a lot of different places but none of their solutions work. This is most likely to do them being for older versions of django or my own stupidity. So I am making a blog type of app that for some reason is called reviews instead of blog... anyway I need to automatically fill up an author field with the username of the logged in user. Here is my models.py:

from django.db import models
from django.contrib.auth.models import User

#vars

# Create your models here.
class reviews(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(User, on_delete=models.PROTECT,)
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True, blank=True)

and forms.py:

from django import forms
from django.forms import ModelForm
from .models import reviews
from django.contrib.auth.decorators import login_required
class CreatePost_form(ModelForm):
    class Meta:
        model = reviews
        exclude = ['author']
        fields = ['title', 'body',]

and views:

from django.shortcuts import render, render_to_response
from .forms import CreatePost_form
from django.http import HttpResponseRedirect

# Create your views here.
def reviewlist(request):
    return render
def index(request, ):
    return render(request, template_name="index.html")
def CreatePost(request):
    form = CreatePost_form(request.POST)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/reviews/succesfulpost')
    return render(request, "reviews/CreatePostTemplate.html", {'form':form})
def succesfulpost(request):
    return render(request, "reviews/succesfulpost.html")

Upvotes: 1

Views: 672

Answers (1)

user1301404
user1301404

Reputation:

def CreatePost(request):
    form = CreatePost_form(request.POST)
    if form.is_valid():
        form.save(commit=False)
        form.author = request.user
        form.save()
        return HttpResponseRedirect('/reviews/succesfulpost')

As simple as that. Rather than actually saving and committing the data, you simply save without committing then you're able to change the value of the excluded field.

Upvotes: 2

Related Questions