django - 扩展用户配置文件

标签 django html

我需要帮助。我在扩展 userprofile 时遇到问题。起初一切似乎都很好,直到现在。请我需要帮助来解决这个波纹管是我的代码。 模型.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()

View .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 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>

我得到的错误

Forbidden (403)

CSRF verification failed. Request aborted. Help

Reason given for failure:

CSRF token missing or incorrect.

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

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

well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

最佳答案

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

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 中导入您的模型用户配置文件

关于django - 扩展用户配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44910792/

相关文章:

django - 如何在不创建新对象的情况下更新 User 对象?

python - 如何在 Django 模板中处理 Jinja2 中的 for/if 循环

django - pre_delete 信号在特定目录中不起作用

javascript - 执行动态添加的社交网络小部件

iphone - 禁用全屏 iphone 视频

python - SQL 计数优化

python - 导入错误: Could not import settings 'mysite.settings' (Is it on sys.路径?): No module named mysite.设置

javascript - 使用 URL 查询运行两个窗口位置

javascript - 无法在一行中对齐单选按钮及其标签

html - 使 flex 元素重叠