如果未以表格形式提供值,则默认情况下不会存储空值?

时间:2019-07-01 08:08:40

标签: python django

我在Django中创建了一个表单。我需要将imagefield设置为可选,所以我给出了required = False。并且在我的模型中我给出了default = None。我的问题是如果用户没有将个人资料图片设置为默认值None不是存储在数据库中?

forms.py

class Register(forms.Form):
    Email = forms.EmailField(widget=forms.TextInput(attrs= 
                                           {"class":"inputvalues"}))
    Username = forms.CharField(widget=forms.TextInput(attrs= 
                            {"class":"inputvalues"}))
    Password = forms.CharField(widget=forms.PasswordInput(attrs= 
                          ({"class":"inputvalues"})))
    Firstname = forms.CharField(widget=forms.TextInput(attrs= 
                    {"class":"inputvalues"}),max_length=30)
    Lastname = forms.CharField(widget=forms.TextInput(attrs= 
                         {"class":"inputvalues"}),max_length=40)
    Confirm_Password = forms.CharField(widget=forms.PasswordInput(attrs= 
                                 ({"class":"inputvalues"})))
    picture = forms.ImageField(required = False)

models.py

class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    image = models.ImageField(upload_to='media',default=None)

views.py

def register(request):
    if request.method == "POST":
        form = Register(request.POST,request.FILES)
        pro=Profile()
        if form.is_valid():
            email = form.cleaned_data['Email']
            User_name=form.cleaned_data['Username']
            Password=form.cleaned_data['Password']
            firstname=form.cleaned_data['Firstname']
            lastname=form.cleaned_data['Lastname']
            user=User.objects.create_user(username=User_name,
                                    password=Password,email=email,
                          first_name=firstname,last_name=lastname)
            if form.cleaned_data['picture']:
                pro.image = request.FILES['picture']
                pro.user = user
                pro.save()
            redirect('/')

1 个答案:

答案 0 :(得分:0)

没有提供图片时,不会保存

pro。 尝试将代码更改为此:

        if form.cleaned_data['picture']:
            pro.image = request.FILES['picture']
        pro.user = user
        pro.save()