Reputation: 193
I have searched a lot on this and all the questions and answers provided are never clear and fit for purpose, maybe I'm going at it the wrong way. I have just recently started Python and Django, so know very little about it. I am creating a website and have done the basic authentication using Django and even added the facebook authentication using social-django. That part all works fine. Now I am moving to profile information and how to update it after you sign up to website.
I have the below UserProfile in models.py:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.TextField()
last_name = models.TextField()
email_address = models.EmailField()
phone_number = models.TextField()
In forms.py a testing form:
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['first_name','last_name','email_address']
Then in views.py I have a function:
def myprofile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
user_profile = UserProfile.objects.get(user=request.user)
if request.method == 'GET':
user_profile = UserProfile.objects.get(user=request.user)
form = UserProfileForm(instance=user_profile)
return render(request, 'pandp/myprofile.html',
{'user_profile' : user_profile, 'form' : form})
And finally myprofile.html:
<div class="profile-details">
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
</form>
</div>
I was struggling from the start to actually only load UserProfile of the logged in User, it seems like I managed to do it using UserProfile.objects.get(user=request.user) and UserProfileForm(request.POST, instance=request.user) but not really sure if it's the right way to do it. Currently my code populates the first_name, last_name and email address in the html form output, but when updating a field and clicking 'Update' button it kind of refreshes but doesn't save to database.
Is the form.save() not enough or I'm doing something wrong?
If you have a suggestion on a much simpler way to do it I'm all ears. I have also tried looking into UpdateView methods but again all examples I found always had gaps and I couldn't fit it for my purpose. Any benefit in using UpdateView over ModelForm?
Long and winded question maybe, but hopefully you got the problem and hopefully this can help other people who have similar issue.
Upvotes: 0
Views: 2162
Reputation: 68
def myprofile(request):
if request.method == 'POST':
user_profile = UserProfile.objects.get(user=request.user)
form = UserProfileForm(request.POST, instance=user_profile)
...
You need to get the UserProfile instance and pass that one to the UserProfileForm, just like @willem-van-onsem mentioned in the comment.
Upvotes: 1