I try to change my profile but when i subbmit my form, it shows CSRF verification failed even when i used csrf_token and CSRF_TRUSTED_ORIGINS.
Here is my models:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
avatar = models.ImageField(default='static/images/default.jpg', upload_to='static/images')
@classmethod
def create(cls, authenticated_user):
profile = cls(user=authenticated_user, name= authenticated_user)
# do something with the book
return profile
def __str__(self):
return self.user.username
My view:
@login_required
def profile(request):
"""Show profile"""
# profile = UserProfile.objects.get(id= request.user)
profile = UserProfile.objects.get(user=request.user)
if request.method != 'POST':
# No data submitted; create a blank form.
form = UserProfileForm(instance=profile)
else:
# POST data submitted; process data.
form = UserProfileForm(instance=profile, data= request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('base:index'))
context = {'profile': profile}
return render(request, 'users/profile.html', context)
My template:
{% if user.is_authenticated %}
<p>Thong tin nguoi dung:</p>
<a>Ten nguoi dung: {{profile.name}}</a>
<p>Anh dai dien: <img src="{{profile.avatar.url}}" alt=""></p>
<form action="{% url 'users:profile'%}" method="post">
{% csrf_token %}
<input type="hidden" name="csrfmiddlewaretoken">
<p>
<label for="id_name">Name:</label>
<input type="text" name="name" maxlength="200" required="" id="id_name">
</p>
<p>
<label for="id_avatar">Avatar:</label>
<input type="file" name="avatar" accept="image/*" id="id_avatar">
</p>
<button name="submit">save changes</button>
</form>
{% else %}
{% endif %}
My setting:
STATIC_URL = '/static/'
STATICFILES_DIRS = [ os.path.join (BASE_DIR, "static"), ]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1']
How can i sumit my form ?
Simply try to add type
to button tag because when you set action to form tag then you must add type
to button tag or input tag.
change this:
<button name="submit">save changes</button>
To this:
<button type="submit">save changes</button>
And see if it solves