为什么我在保存Django表单时遇到ValueError

时间:2018-03-30 18:48:40

标签: python django python-3.x django-forms

model.py

class User(models.Model):
    ImageKitConf.CACHEFILE_DIR = 'uploads/200/'

    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=20)
    username = models.CharField(max_length=30, unique=True)
    password = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    phone = models.CharField(max_length=20)
    address = models.CharField(max_length=100)

    photo = models.ImageField(upload_to='uploads/200/', default='uploads/200/default.png', blank=True)
    thumb = ImageSpecField(
        source=photo,
        processors=[SmartResize(200,200)],
    )
    role = models.ForeignKey('Role', default=3, on_delete=models.CASCADE)
    is_active = models.BooleanField(default=True)
    activation_code = models.CharField(max_length=50)
    password_reset_code = models.CharField(max_length=50, default=0)

form.py

class Registration_Form(forms.ModelForm):
    CHOICES = [('1', 'Active',), ('0', 'Inactive',)]
    is_active  = forms.ChoiceField(label='Is Active', choices=CHOICES, required=True, widget=forms.RadioSelect())
    user_title = forms.ModelChoiceField(label='User Role', empty_label='--- Select a Role ---',queryset=Role.objects.all() , widget=forms.Select(attrs={'class': 'span8'}),required=True)
    class Meta:
        model = User
        exclude = ('activation_code', 'password_reset_code', 'role')
        widgets = {
            'first_name' : forms.TextInput(attrs= {'type':'text', 'placeholder': "First Name", 'class': 'span8', 'title': 'First Name'}),
            'last_name'  : forms.TextInput(attrs= {'type':'text', 'placeholder': "Last Name", 'class': 'span8', 'title': 'Last Name'}),
            'username'   : forms.TextInput(attrs= {'type':'text', 'placeholder': "User Name", 'class': 'span8', 'title': 'User Name'}),
            'password'   : forms.TextInput(attrs= {'type':'password', 'placeholder': "Password", 'class': 'span8', 'title': 'Password'}),
            'email'      : forms.TextInput(attrs= {'type': 'text', 'placeholder': "Email Address", 'class': 'span8', 'title': 'Email'}),
            'phone'      : forms.TextInput(attrs= {'type':'text', 'placeholder': "Phone Number", 'class': 'span8', 'title': 'Start with +88', 'pattern': '^[\+][8][8]\d{11}'}),
            'address'    : forms.TextInput(attrs= {'type':'text', 'placeholder': "Address", 'class': 'span8', 'title': 'Address'}),
            'photo'      : forms.FileInput()

        }

views.py

def registration(request):
    form = Registration_Form()
    if request.method == 'POST':
        form_values = Registration_Form(request.POST, request.FILES)
        if form_values.is_valid:
            form_values.save(commit=False)
            return redirect('Users:registration')

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

我收到此错误

Internal Server Error: /users/registration/ Traceback (most recent call last): 
File "D:\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
File "D:\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
File "D:\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "G:\DJANGO PROJECTS\Login_and_Registration\Users\views.py", line 65, in registration
    form_values.save(commit=False)
File "D:\Anaconda3\lib\site-packages\django\forms\models.py", line 451, in save
    'created' if self.instance._state.adding else 'changed', ValueError: The User could not be created because the data didn't validate. [31/Mar/2018 00:40:49] "POST /users/registration/ HTTP/1.1" 500 76566

1 个答案:

答案 0 :(得分:1)

问题是你有form_values.is_valid而不是form_values.is_valid()

方法form_values.is_valid将始终评估为True,这意味着您正在尝试保存表单,即使表单无效也是如此。您需要使用form_values.is_valid()调用该方法。

您应将其更改为:

if form_values.is_valid():
    form_values.save(commit=False)