Adrian0012
Adrian0012

Reputation: 185

RelatedObjectDoesNotExist at /post/new/ - Post has no author

I have implemented allauth for user registration and now I am trying to associate the current_user to a post when its being created. When I press 'Submit' I get 'Post has no author' clearly the posts don't recognize the user.

Model:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
  title = models.CharField(max_length=100)
  content = models.TextField()
  date_posted = models.DateTimeField(default=timezone.now)
  author = models.ForeignKey(User, on_delete=models.DO_NOTHING)

  def __str__(self):
    return self.title

View:

def create_post(request, pk=None):


form = PostForm(request.POST)

  if form.is_valid():
    post = form.save(commit=False)
    post.author(request.user)
    post.save()
  else:
    form = PostForm()

  context = {'form' : form}
  return render(request, 'blog/create_post.html', context)

I could really use some pointers, many thanks.

Upvotes: 1

Views: 382

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You can set the author instance of the .instance wrapped in the form:

from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect

@login_required
def create_post(request, pk=None):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.instance.author = request.user
            form.save()
            return redirect('name-of-a-view')
    else:
        form = PostForm()
    context = {'form' : form}
    return render(request, 'blog/create_post.html', context)

Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

 

Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.

Upvotes: 1

Related Questions