Running into a "Cannot assign... must be a ...instance" error

7,380 views
Skip to first unread message

Joey Jo Jo Jr

unread,
Mar 4, 2020, 5:28:48 PM3/4/20
to Django users
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 %}

Sachin Ranadive

unread,
Mar 5, 2020, 5:15:50 PM3/5/20
to django...@googlegroups.com
Change view code, assign User object instead.

author = User.objects.get(username=request.POST["username"])

Sachin

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e0bb05c3-ecee-4f75-97ca-a659cb7e6181%40googlegroups.com.

Sachin Ranadive

unread,
Mar 5, 2020, 5:16:00 PM3/5/20
to django...@googlegroups.com
Or ignore the form username field;

author=request.user

Sachin Ranadive
Reply all
Reply to author
Forward
0 new messages