Answer the question
In order to leave comments, you need to log in
How to assign the name of the current user as the author of an article?
I don't understand why this code doesn't work.
models.py
class Article(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
)
text = models.CharField(
"Article text",
max_length=128,
null=False,
blank=False,
)
from myapp.models import Article
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = (
'text',
)
@login_required
def article(request):
if request.method == "POST":
form = ArticleForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "Создана запись в базе данных!")
return HttpResponseRedirect('/form-ok/')
else:
form = ArticleForm()
context = {
"form": form
}
return render(request, 'article.html', context)
Answer the question
In order to leave comments, you need to log in
instance.author = request.user
If the user is authorized, of course.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question