How can I automatically assign the current user as the author when creating a post?

How can I automatically assign the current user as the author when creating a post?

forms:

from django import forms
from publication.models import Userpublication

class PostForm(forms.ModelForm):
    content = forms.CharField(label='',widget=forms.Textarea(attrs={'class': 'content_toggle app-textarea',
                                                                'utofocus': 'true',
                                                                'maxlength': '250',
                                                                'placeholder': 'hello',
                                                                'required': True}))

    class Meta:
        model = Userpublication
        fields = ['content', 'author'] 
        labels = {
            'Content': False,
        }

views:

def create_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST, initial={'author': request.user})
        
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = PostForm(initial={'author': request.user})
    post_lists = Userpublication.objects.all()
    context = {
        'form': form,
        'post_lists': post_lists,
    }
    return render(request, 'twippie/home.html', context)

enter image description here

This is how it works.

But as soon as I remove fields 'author' from the form, but 'content' remains, the following error appears:

File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages
django\db\backends\sqlite3\base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.IntegrityError: NOT NULL constraint failed: publication_userpubl ication.author_id

the browser shows this error:

IntegrityError at /feed/ NOT NULL constraint failed: publication_userpublication.author_id

What could I have missed or overlooked?

model if needed:

from django.db import models
from autoslug import AutoSlugField
from django.urls import reverse
from django.contrib.auth.models import User
from django.conf import settings 

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(is_published=1).order_by('-time_create')

class Userpublication(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)  
    slug = AutoSlugField(max_length=255, unique=True, populate_from='content')
    content = models.TextField('', blank=True)
    time_create = models.DateTimeField('time create ', auto_now_add=True)
    time_update = models.DateTimeField('time update ', auto_now=True)
    is_published = models.BooleanField('is published', default=True)

    objects = models.Manager()
    published = PublishedManager()

    def __str__(self):
        return self.slug

    class Meta:
        ordering = ['-time_create']
        indexes = [
            models.Index(fields=['-time_create'])
        ]

    class Meta:
        verbose_name = 'Post'
        verbose_name_plural = 'Posts'

    def get_absolute_url(self):
        return reverse('post_detail', kwargs={'post_slug': self.slug})

    def get_edit_url(self):
        return reverse('edit_post', kwargs={'post_slug': self.slug})

I tried to remove the author from the form, but it gave me an error. And I need the author to be automatically set in the 'author_id' field

Just get the user from the request (@see Django DOCs) & set this field afterwards in your form.

def create_post(request):
    user = request.user
    ...

I solved my issue. The matter turned out to be much simpler. I have one of the applications that is responsible for the form of publishing and displaying posts. In application 2, exactly the same view function was added. All I had to do was remove it and everything worked. That's why it gave an error.

Back to Top