无法更新自定义用户 (AbstractUser)

Posted

技术标签:

【中文标题】无法更新自定义用户 (AbstractUser)【英文标题】:Cannot Update Custom User (AbstractUser) 【发布时间】:2021-03-06 18:05:05 【问题描述】:

我正在使用从 AbstractUser 继承的自定义用户模型,当我保存用户时它运行良好。 但是当我需要更新模型并单击模板上的提交按钮时,什么也没有发生。控制台中什么都没有显示,页面没有重新加载,什么都没有。 我真的很感激这里的一些指导?


#models 
from django.core.validators import RegexValidator
from sos.models import Company 
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import MinValueValidator, MaxValueValidator
from django.urls import reverse  # page 138 Django for Beginneers 

# Create your models here.

#  https://***.com/questions/19130942/whats-the-best-way-to-store-phone-number-in-django-models/19131360

class CustomUser(AbstractUser):
    position = models.CharField(max_length=30, null=True )   
    email = models.EmailField(null=True, blank=False, unique=True )
    phone_regex = RegexValidator(regex=r'^\+?1?\d9,15$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    mobile_phone = models.CharField(validators=[phone_regex], max_length=17, blank=False, null=True, unique=True)
    date_created = models.DateTimeField(auto_now_add=True, editable=True)
    is_staff = models.BooleanField(verbose_name="Is Staff Admin?", help_text="Designates whether this user should be able to log in the Admin Interface.")
    company = models.ForeignKey(Company , on_delete=models.CASCADE, verbose_name="Company Name") 
    
    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse("customuser_detail", args=[str(self.id)])

    class Meta:
        ordering = ["username"] 
# forms
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from .models import CustomUser
from .models import UserTargets

# cripsy forms imports 
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Column, Layout, Field, Fieldset, Div, Row, html, ButtonHolder, Submit
from crispy_forms.bootstrap import TabHolder, Tab

#  3rd Party
from .custom_layout_object import Formset

# forms 

from django import forms
from django.forms import ModelForm, Textarea
from django.forms.models import inlineformset_factory 

import re


class CustomUserChangeForm(UserChangeForm):
    password = None 

    class Meta:
        model = CustomUser
        fields = '__all__'
        # fields = ('username', 'first_name', 'last_name', 'password1','password2','is_staff', 'is_active' ,'email','position','mobile_phone','is_active','company')
        # fields = UserCreationForm.Meta.fields + ('email','position','mobile_phone','company')
        
    def __init__(self, *args, **kwargs):
        super(CustomUserChangeForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False # use false if you want to render the form tags manually
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-10'
        self.helper.attrs['autocomplete'] = 'off'
        self.helper.layout = Layout(

                Div(
                    Field('username'),
                    Field('first_name'),
                    Field('last_name'),
                    # Field('password'),
                    # Field('password2'),
                    Field('email'),
                    Field('position'),
                    Field('is_staff'),
                    Field('is_active'),
                    Field('mobile_phone'),
                    Field('company'),

                HTML("<br>"),
                ButtonHolder(Submit('submit', 'Save', css_class='btn btn-primary btn-xs')),
                
                )
        )

# views

class CustomUserUpdateView(UpdateView):
    model = CustomUser
    form_class = CustomUserChangeForm
    template_name = 'accounts/user_profiles/customuser_edit.html'
#urls 
 path('profiles/<int:pk>/edit', views.CustomUserUpdateView.as_view() , name='customuser_edit'),
# templates
% extends "base.html" %
% load crispy_forms_tags %
% load static %

% block extrahead %

   form.media 

  % endblock %


% block content %

<div class="container">
    <div class="card">
        <div class="card-header">
            Edit User Profile  
        </div>
        <div class="card-body">
            % csrf_token %
             % crispy form %

             <br>           
             <a> <input type="submit" value="Update" class="btn btn-primary btn-xs" /></a>
             <a href="% url 'customuser_list' %"> |All Users </a>
         </div>
    </div>  
 </div>
<!--  https://github.com/django-crispy-forms/django-crispy-forms/issues/65  -->

% endblock content %

【问题讨论】:

表单标签在哪里?? 我正在使用 Django 脆皮表单,因此表单标签使用脆皮表单呈现。 self.helper.form_tag = False # use false if you want to render the form tags manually 这是你自己代码中的一行... 我不确定你在上一条评论中所说的 Abdul. 【参考方案1】:

页面渲染完成后,查看页面源代码。 检查脆的表单是否真的包含表单标签。

我以前没有使用过脆的表格,但我不得不问,你不应该以某种方式描述表格的结束位置吗?

也许你错过了什么...

% end crispy forms %

【讨论】:

以上是关于无法更新自定义用户 (AbstractUser)的主要内容,如果未能解决你的问题,请参考以下文章

Django自定义用户表替换默认用户表认证

在 Django 1.5 自定义用户模型中使用电子邮件作为用户名字段导致 FieldError

为后端的每个用户创建 Django User 对象

Django自定义UserModel并实现认证和登录

自定义 Django的User Model,扩展 AbstractUser类注意事项

django自定义用户表