我的表单没有选择图像文件

时间:2017-06-10 20:34:46

标签: html django

到目前为止,一切运作良好 但我面临的唯一问题是上传imagefile..Image字段不导入所选图片。请帮助和谢谢

这是我的个人资料表格的model.py

class UserProfile(models.Model):

   user = models.OneToOneField(User,unique=True,on_delete=models.CASCADE)
   bio = models.TextField(max_length=500,null=True,blank=True)
   picture = models.ImageField(upload_to="profile_image",null=True)
   company = models.CharField(max_length=500,null=True)


   def __str__(self):
       return self.user.username

# Sending a new signal when ever a user is created to create a new profile
@receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
    if created:
       UserProfile.objects.create(user=instance)

这是我的view.py

@login_required
@transaction.atomic

def update_profile(request):
    if request.method == 'POST':

       profile_form = 
       ProfileForm(request.POST,instance=request.user.userprofile)
       if  profile_form.is_valid():

        profile_form.save()
        messages.success(request,'Your Profile has been Updated')
        return redirect('success:profile_account')
       else:
          messages.error(request,'fill out the fields correctly')
     else:

         profile_form = ProfileForm(instance=request.user.userprofile)
    return render(request,"success/user_account/edit_profile.html",
    {'profile_form':profile_form})

这是form.py

class ProfileForm(forms.ModelForm):
class Meta:

    model= UserProfile
    exclude=['user',]

    fields =['bio','picture','company']

这是用于呈现我的更新的hmtl文件

                <h4>{{ user.get_username }}</h4>
                <h4> {{ user.get_full_name}}</h4>
                <h4> {{ user.first_name}}</h4>
                <h4> {{ user.email}}</h4>
                <h4> {{ user.bio}}</h4>
                <h4> {{ user.userprofile.company }}</h4>SS
                <h4>{{user.userprofile.bio}}</h4>
                {% if user.userprofile.picture %}
                <image src="{{user.userprofile.picture.url}}" width="40" height="40">
                    {% else %}
                    <p> Chose a profile</p>
                    {% endif %}

                </image>
                <a href="{% url 'success:Profile_update' %} ">Update</a>
            </li>

这是我的Edit.html文件

    {%csrf_token%} {{profile_form.as_p}}保存更改

1 个答案:

答案 0 :(得分:0)

修改您的观点,

def update_profile(request): 
    if request.method == 'POST':
        profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.userprofile) 
        if profile_form.is_valid():
            profile_form.save()
            messages.success(request,'Your Profile has been Updated')
            return redirect('success:profile_account')
        else: 
            messages.error(request,'fill out the fields correctly') 
    else: 
        profile_form = ProfileForm(instance=request.user.userprofile) 
    return render(request,"success/user_account/edit_profile.html", {'profile_form':profile_form})

您需要在表单初始化中指定request.FILES,以便使用Django表单上传文件。