S
S
sazhyk2016-11-24 12:18:46
Django
sazhyk, 2016-11-24 12:18:46

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,
    )

forms.py
from myapp.models import Article
class ArticleForm(ModelForm):
    class Meta:
        model = Article
        fields = (
            'text',
        )

views.py
@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)

I think the essence is clear: it is simplified here, but the user creates a record and it is necessary that a record be created in the database with the fields "article_text" and "article_author".
I have read it here , and even here .

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2016-11-24
@sazhyk

instance.author = request.user
If the user is authorized, of course.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question