我试图更改我的配置文件,但是当我提交表单时,它显示即使我使用csrf_token和CSRF_TRUSTED_ORIGINS,CSRF验证也失败了。
这是我的模特:
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我的看法是:
@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)我的模板:
{% 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 %}我的背景:
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']我怎样才能总结我的表格?
发布于 2022-11-19 05:41:37
只需尝试将type添加到按钮标记,因为当您将操作设置为form标记时,必须将type添加到按钮标记或输入标记中。
改变这一点:
<button name="submit">save changes</button>对此:
<button type="submit">save changes</button>看看能不能解决
https://stackoverflow.com/questions/74497521
复制相似问题