New to Django.
I'm trying to set up a simple comment form where I can add a title for the comment, content of the comment, and attach the username of the user that is currently signed in and posting it.
I run into the following error when running it:
Cannot assign "'john'": "Entry.author" must be a "User" instance.
I think I understand what's happening here, however I'm having a hard time figuring out how to implement it properly.
Here's my model code:
class Entry(models.Model):
title = models.CharField(max_length=60)
content = models.TextField(max_length=500)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
def __str__(self):
return f"{self.id}"
Here's my view code:
@login_required
def add(request):
if request.method == "POST":
entry = Entry(
title = request.POST["title"],
content = request.POST["content"],
author = request.POST["username"]
)
entry.save()
return render(request, "articles/index.html", {
"entries": Entry.objects.all()
})
else:
return render(request, "articles/add.html", {
"username": request.user
})
And here's my form code in my template:
{% block body %}
<h1>New Entry</h1>
<form action="{% url 'add' %}" method="post">
{% csrf_token %}
<input type="hidden" name="username">
<label for="title">Title:</label>
<input type="text" name="title" placeholder="Entry Title">
<br>
<label for="content">Content:</label>
<textarea name="content">
Content goes here
</textarea>
<br>
<input type="submit" value="Publish">
</form>
{% endblock %}