0

有人可以帮我编写 forms.py views.py 和 urls 的代码吗?视图.py

def PasswordRecover(request):
    if request.method=='POST':
        form=UserGet(request.POST)
        user= form.save(commit=False)
        if(user.is_active):
            return redirect('password_reset/security',pk=user.pk)
    else:
        form = UserGet()

    return render(request, 'passwordreset.html', {'form':form})

def Security(request):
    return HttpResponse('what do we add here??')

表格.py:

class UserGet(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ('username',)

网址.py:

from django.urls import path
from . import views

app_name='users'
urlpatterns = [
    path('signup/', views.SignUp.as_view(), name='signup'),
    path('password_reset',views.PasswordRecover,name='password_recovery'),
    path('password_reset/security',views.Security,name='SecurityRecover'),
]

我得到的错误:异常值:无法创建 CustomUser,因为数据未验证。

自定义用户模型:

class CustomUser(AbstractUser):
    # First/last name is not a global-friendly pattern
    name = models.CharField(blank=True, max_length=255)
    MALE = 'M'
    FEMALE = 'F'
    GENDER_CHOICES=(
        (MALE,'Male'),
        (FEMALE,'Female'),
    )
    gender = models.CharField(max_length=1,choices=GENDER_CHOICES,default=MALE)
    bio = models.CharField(max_length=255,blank=True)
    DOG = 'DOG'
    PHONE = 'PHONE'
    USER_QUESTIONS = (
        (DOG, 'Dog'),
        (PHONE, 'Phone'),
    )
    user_questions = models.CharField(max_length=255,choices=USER_QUESTIONS, default=DOG)
    answer = models.CharField(max_length=255,blank=True)


    def __str__(self):
        return self.email

注册视图:

class SignUp(generic.CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

表格.py:

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, UsernameField
from .models import CustomUser



class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('username', 'email', 'gender', 'user_questions', 'answer')


class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = CustomUser
        fields = UserChangeForm.Meta.fields

这是我的文件。我不知道我该如何进一步

4

1 回答 1

0

回答您的错误:

在保存 [ user= form.save(commit=False)] 表单之前,您必须验证表单。

像这样的东西:

if form.is_valid():
    user= form.save(commit=False)
else:
    render(request, 'passwordreset.html', {'form':form})

关于您的安全问题查询的建议:

我认为您可以在CustomUser模型中有两个字段,一个用于安全问题(可能基于选项?),另一个用于用户回答。然后根据您的逻辑,您可以在视图中实现它。或者,如果您也需要我的帮助,请告诉我您的逻辑。

于 2018-06-22T08:25:10.753 回答