Django FileField属性没有与之关联的文件,也没有上传图像

时间:2018-05-30 09:45:34

标签: django python-3.x file

我想要几个小时但没有运气。我之前上传了文件,但不知道这里发生了什么。请检查代码。

自定义用户模型:

class User(AbstractBaseUser):

objects = UserManager()

username =  models.CharField(max_length=250)
email   =  models.EmailField(max_length=255,unique=True)
active  =  models.BooleanField(default=True)
admin  =  models.BooleanField(default=False)
staff  =  models.BooleanField(default=False)
type = models.CharField(max_length=250)
job = models.CharField(max_length=250,blank=True)
workplace = models.CharField(max_length=250,blank=True)
description_of_user = models.CharField(max_length=250,blank=True)
profile_picture = models.FileField(upload_to='profile_pics/',blank=True)



USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username','type']   


def __str__(self):
    return self.email

def get_full_name(self):
    return self.email

def get_short_name(self):
    return self.email 

def has_perm(self,perm,obj=None):
    return True

def has_module_perms(self,app_label ):
    return True

@property
def is_staff(self):
    return self.staff

@property
def is_staff(self):
    return self.staff


@property
def is_admin(self):
    return self.admin

@property
def is_active(self):
    return self.active

forms.py:

class userRegistrationForm(forms.ModelForm):

password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Your Password'}))
password2 = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}))
email = forms.CharField(max_length=30,widget=forms.TextInput(attrs={'placeholder': 'Your Email address'}))
email2 = forms.CharField(max_length=30,widget=forms.TextInput(attrs={'placeholder': 'Confirm email'}))


class Meta:
    model = User
    fields = ('username','email','type','password','job','workplace','profile_picture','description_of_user')
    widgets={

                # "description":forms.TextInput(attrs={'placeholder':'description','name':'description','id':'common_id_for_imputfields','class':'input-class_name'}),
                "username":forms.TextInput(attrs={'placeholder':'Your username'}),                  
                "email":forms.TextInput(attrs={'placeholder':'Email'}),
                "password":forms.TextInput(attrs={'placeholder':'Password'}),
                "type" : forms.HiddenInput(attrs={'value':'consumer'}),
                "job" : forms.TextInput(attrs={'placeholder':'Your Job'}),
                "description_of_user" : forms.TextInput(attrs={'placeholder':'Enter a short description about yourself'}),
                "workplace" : forms.TextInput(attrs={'placeholder':'Your current workplace'}),

              } 


def clean(self,*args,**kwargs):

    email =  self.cleaned_data.get("email")
    email2 =  self.cleaned_data.get("email2")
    password =  self.cleaned_data.get("password")
    password2 =  self.cleaned_data.get("password2")

    if email!=email2 :
        raise forms.ValidationError("Emails must match")

    if password!=password2 :
        raise forms.ValidationError("Passwords must match")

    email_query = User.objects.filter(email=email)

    if email_query.exists():
        raise forms.ValidationError("This email has been registered")

    return super(userRegistrationForm,self).clean(*args,**kwargs)   

模板渲染:

        {% extends 'base_template.html' %}

        {% load staticfiles %}

        {% block css %}

        <link type="text/css" rel="stylesheet" href="{% static 'css/styleUserRegistration.css' %}"/>
        <link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>

        {% endblock %}




            {% block content %}


        <div class="wrapper">
          <h1>Register For An Account</h1>
          <p>To sign-up for a free basic account please provide us with some basic information using
          the contact form below. Please use valid credentials.</p>

          <form class="form" method="post" action="{% url 'signup' %}" enctype="multipart/form-data" >

            {% csrf_token %}


                                    {{form.username}}
                                    {{form.email}}
                                    {{form.email2}}
                                    {{form.password}}
                                    {{form.password2}}
                                    {{form.type}}
                                    {{form.job}}
                                    {{form.workplace}}
                                    {{form.description_of_user}}
                                    {{form.profile_picture}}
            </br>

            <input type="submit" class="submit" value="Register">


          </form>
        </div>


        {% endblock %}

views.py:

def signup(request):

form = userRegistrationForm(request.POST or None)

if form.is_valid() :

    user = form.save(commit = False)

    username = form.cleaned_data.get('username')
    email = form.cleaned_data.get('email')
    password = form.cleaned_data.get('password')


    user.set_password(password)

    user.save()

    new_user = authenticate(email=email,password = user.password)

    login(request,user)

    return redirect('/')


return render (request,"registrationsForm.html",{"form" :form})

除FileField外,表单已成功保存。它无法在此处获取文件。因此它将profile_picture存储为空白。无法弄清楚发生了什么。

1 个答案:

答案 0 :(得分:3)

对于上传文件,您还应通过request.FILES形成初始化:

form = userRegistrationForm(request.POST or None, request.FILES or None)

您可以在Django File Uploads

中找到详细信息