扩展用户个人资料

时间:2017-07-04 16:40:02

标签: django html5

我需要帮助。我在扩展userprofile方面遇到了问题。到目前为止,一切似乎都运转正常。请在解决此问题时需要帮助。我的代码。     Model.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令牌。在登录后登录其他浏览器选项卡或点击后退按钮后,您可能需要   使用表单重新加载页面,因为令牌在a之后旋转   登录。

     

您正在查看此页面的帮助部分,因为您有DEBUG =   您的Django设置文件中为True。将其更改为False,仅更改为   将显示初始错误消息。

     

您可以使用CSRF_FAILURE_VIEW设置自定义此页面。

1 个答案:

答案 0 :(得分:0)

这是扩展用户模型配置文件的最佳方式

from django.contrib.auth.models import AbstractBaseUser
from django.db import models
from django.contrib.auth.models import BaseUserManager


class AccountManager(BaseUserManager):
    def create_user(self, username, password=None, **kwargs):
        if not username:
            raise ValueError('Users must have a valid email username.')

        if not kwargs.get('email'):
            raise ValueError('Users must have a valid email.')

        email = kwargs.get('email')
        account = self.model(
            username=username, email=self.normalize_email(email)
        )

        account.set_password(password)
        account.save()

        return account

    def create_superuser(self, username, password, **kwargs):
        account = self.create_user(username, password, **kwargs)

        account.is_admin = True
        account.save()

        return account

class Account(AbstractBaseUser):    
    username = models.CharField(max_length=40, unique=True)
    email = models.EmailField(unique=True)

    first_name = models.CharField(max_length=40, blank=True)
    last_name = models.CharField(max_length=40, blank=True)

    is_admin = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = AccountManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'first_name', 'last_name']

    def __unicode__(self):
        return self.email

    def get_full_name(self):
        return ' '.join([self.first_name, self.last_name])

    def get_short_name(self):
        return self.first_name

修改此示例,然后在forms.py中导入您的模型用户配置文件