Value Error while storing data into models in Django
This is my "models.py":
class PostData(models.Model):
#image = models.ImageField(upload_to="")
title_name = models.CharField(max_length=255)
description = models.CharField(max_length=10000)
author = models.ForeignKey(User, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
This is my "views.py":
def createPost(request):
if request.method == "POST":
form = PostForm(request.POST)
print(form.is_valid())
if form.is_valid():
# To extarct data from web page
title = form.cleaned_data['title_name']
description = form.cleaned_data['description']
# To get username which is stored in session
author = request.session.get("username")
print(author)
print(title)
# To store Data
PostData.objects.create(title_name=title, description=description, author=author)
And I am getting the following error: ValueError at /create/ Cannot assign "'dhruv123'": "PostData.author" must be a "User" instance. So how to solve this error?
Your request.session.get("username")
is not a django User instance.
author = User.objects.get(name = request.session.get("username"))
Depending on your request.session
.
In PostData model, you have created a relationship between the PostData model and the User model. This relationship is formed through ID. That is, the user ID is stored in the PostData's table. So, at the time of creating the PostData, you either have to give it the user ID, or you have to give the user instance. There are two ways:
- In Django, if the requesting user is logged in, you can get the user from the request and give the instance to the PostData model.
PostData.objects.create(title_name=title, description=description, author=request.user)
- Via the username, first make a query to the user table and get the user instance, then pass it to the PostData.
author = User.objects.get(username=request.session.get('username'))
PostData.objects.create(title_name=title, description=description, author=author)
I suggest you use the first method. Because the first method makes one less request to the database than the second method. As a result, the API latency becomes lower.
When creating a PostData
record, PostData.author
is required to be an instance of User
or the primary_key
of a User
. This is so that the database can create a Many to One relationship between PostData
and User
.
You are passing a value 'dhruv123'
which is neither an instance of User
nor the primary_key
of a User
. First get a User
using:
username = request.session.get("username")
user = User.objects.get(username=username)
Then create a PostData
with the User
retrieved:
PostData.objects.create(title_name=title, description=description, author=user) #[1]
[1] The assumption here is that User
is django.contrib.auth.models.User
.