Save User First_name As Default Value For Model Django
I have an article model with author variable which I want to save as the users first and last name. I use custom user model called Account. author = models.CharField('author',max_l
Solution 1:
You need to provide some default value like this in CharField.
author = models.CharField('author',max_length=50, default='First Name')
You can save the user(current user) first name in your author field like this while saving the form.
if request.method == "POST":
form = ArticleCreationForm(request.POST)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user.first_name # the user must be logged in for this.
article.save()
return redirect('some_path')
Solution 2:
you can use the below mentioned codes for generating the author model and use it corresponding to the post they create :
from django.contrib.auth import get_user_model
User = get_user_model()
classAuthor(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField()
def__str__(self):
return self.user.username
and you can call this user/author where u need in your model using :
author = models.ForeignKey(Author, on_delete=models.CASCADE)
Post a Comment for "Save User First_name As Default Value For Model Django"