【发布时间】:2017-07-04 16:40:02
【问题描述】:
我需要帮助。我在扩展用户配置文件时遇到问题。起初一切似乎都运行良好,直到现在。请我需要帮助来解决这个问题,下面是我的代码。 模型.py
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofile")
date =models.DateField(blank=False,null= True)
bio = models.TextField(max_length=500,blank=False)
picture = models.ImageField(upload_to="profile_image",null=True,blank=True)
company = models.CharField(max_length=500,null=True)
def __str__(self):
return self.user.username
@receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(post_save,sender=User)
def save_user_profile(sender,instance,**kwargs):
instance.UserProfile.save()
views.py
def update_profile(request):
if request.method == 'POST':
profile_form = ProfileForm(request.POST,request.FILES,instance=request.user.userprofile)
if profile_form.is_valid():
profile_form.save()
messages.success(request,'Your Profile has been Updated')
return redirect('success:profile_account')
else:
messages.error(request,'fill out the fields correctly')
else:
profile_form = ProfileForm(instance=request.user.userprofile)
return render(request,"success/user_account/edit_profile.html",{'profile_form':profile_form})
html.form
<form action='{{ action_url }}' method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ profile_form.bio}}{{profile_form.bio.error}}
{{ profile_form.picture}}{{profile_form.picture.error}}
<div class="pc"><label>Company Name:</label>{{ profile_form.company}}{{profile_form.company.error}}
{{ profile_form.date}}{{profile_form.date.error}}
<button type="submit">Save changes</button>
我得到错误
禁止 (403)
CSRF 验证失败。请求中止。帮助
失败原因:
CSRF token missing or incorrect.通常,当有真正的跨站点请求时,可能会发生这种情况 伪造,或者没有正确使用 Django 的 CSRF 机制。 对于 POST 表单,您需要确保:
Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as以及那些接受 POST 数据的人。 该表单具有有效的 CSRF 令牌。在另一个浏览器选项卡中登录或在登录后点击返回按钮后,您可能需要 使用表单重新加载页面,因为令牌在 登录。
您看到此页面的帮助部分是因为您有 DEBUG = 在您的 Django 设置文件中为真。将其更改为 False,并且只有 将显示初始错误消息。
您可以使用 CSRF_FAILURE_VIEW 设置自定义此页面。
【问题讨论】:
-
我不知道这是否重要,但您是否关闭了表单标签?