I'm trying to initialize some fields of my NewArticleForm with static data. In particular, I want to set the author field with the current logged user/author, and shouldn't be modifyable. This page is reachable only from logged user, and the information is also stored in the url:
path('<int:user_id>/create', views.add_article, name='insert'),
forms.py:
class NewArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['author','title', 'content', 'pub_date']
pub_date = forms.DateTimeField(initial=timezone.now())
def save(self, commit=True):
article = super(NewArticleForm, self).save(commit=False)
if commit:
article.save()
return article
models.py:
from django.db import models
from django.contrib.auth.models import User
class Article(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
pub_date = models.DateTimeField()
title = models.CharField(max_length=50)
content = models.TextField()
def __str__(self):
return self.title
def get_year(self):
return self.pub_date.year
def get_month(self):
return self.pub_date.month
views.py:
@login_required
def add_article(request, user_id):
if request.method == 'POST':
form = NewArticleForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Articolo inserito con successo!')
return redirect('/blog_app/')
else:
messages.warning(request, 'Qualche campo non è corretto, operazione fallita.')
form = NewArticleForm()
return render(request, template_name='blog_app/insert.html', context={'insert_form':form})
How can I set author with the current logged user?
Bonus question: Why pub_date field, which is a DateTimeField, is displayed as text type? I can't change it.