1👍
✅
Your view currently creates a new Author
record each time you "update" the model. I would advise to first clean up the database and remove all authors.
Then you can convert the ForeignKey
into a OneToOneField
here: that way we know that each user has at most one Author
:
from django.conf import settings
class Author(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
# …
Now we can alter the view to create a record in case there is no such record, or update an existing record if there is one:
from .forms import UpdateForm
def update_profile(request):
context = {}
user = request.user
instance = Author.objects.filter(user=user).first()
if request.method == 'POST':
form = UpdateForm(request.POST, request.FILES, instance=instance)
if form.is_valid():
form.instance.user = user
form.save()
return redirect('/')
else:
form = UpdateForm(instance=instance)
context.update({
'form': form,
'title': 'update_profile',
})
return render(request, 'register/update.html', context)
In the template, you can render data of the related Author
model for a user user
with:
{{ user.author.fullname }}
{{ user.author.bio }}
Source:stackexchange.com