I am trying to update an object named User with the properties username and fullname; my model is below.
class User(models.Model):
"""docstring for User"""
fullname = models.TextField()
username = models.TextField()
password = models.TextField()
createdDate = models.DateTimeField(default=timezone.now)
publishedDate = models.DateTimeField(blank=True, null=True)
def publish(self):
self.publishedDate = timezone.now
self.save()
def __str__(self):
return str("\npk= " + self.pk + " | fullname= " + self.fullname + " | username= " + self.username + "\n")
I have created an edit page and am able to get the values from that page in my view through request.POST["fullname"] and request.POST["username"].
My question is how do I update the entire object without having to specify a specific property in update or without getting the object and setting my new values and saving the object; my view is below.
def editUserByID(request, userID):
if (request.method == "POST"):
if (request.POST["userID"] != '' and request.POST["fullname"] != '' and request.POST["username"] != ''):
user1 = User(
pk=request.POST["userID"],
fullname=request.POST["fullname"],
username=request.POST["username"]
)
print(user1)
# this only updates 1 property, so for multiple properties I would have to write multiple statements
User.objects.filter(pk=user1.pk).update(fullname=user1.fullname)
# is this possible? send the entire object and have it update the DB
User.objects.filter(pk=user1.pk).update(user1)
# this is how I was able to save it, but have to get the existing object again, assign the new values and then save
updateUser = User.objects.get(pk=user1.pk)
updateUser.fullname=user1.fullname
updateUser.username=user1.username
updateUser.save()
else:
user2 = User.objects.get(pk=userID)
return render (request, 'helloworld/editUser.html', {'user': user2})
return redirect('listUsers')
PS: I have been working with Java and .NET until now but am completely new to Python/Django so any help would be highly appreciated.