代码之家  ›  专栏  ›  技术社区  ›  Yunus

django filefield属性没有与其关联的文件,也没有上载图像

  •  0
  • Yunus  · 技术社区  · 6 年前

    我试了好几个小时,但没有运气。我以前上传过文件,但不知道这里发生了什么。请检查密码。

    自定义用户模型:

    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 %}
    

    视图.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除外。无法在此处获取文件,因此将个人资料图片存储为空白。不知道发生了什么。

    1 回复  |  直到 6 年前
        1
  •  3
  •   neverwalkaloner    6 年前

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

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

    您可以在 Django File Uploads .