Django图像没有保存

时间:2016-03-19 10:44:36

标签: django

我正在尝试通过 ImageField 上传图片。我收到了http 200,但图片没有得到保存。

我的模特是:

class RestaurantProfile(BaseModel):
    username = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    phone = models.CharField(max_length=15)
    address = models.TextField(default='', blank=True)
    restaurant_image = models.ImageField(upload_to='restaurants', blank=True, null=True)

我的表格是:

class UpdateDetailsForm(forms.Form):
    phone = forms.CharField(widget=forms.NumberInput(attrs={'class': 'form-control input-glass', 'id': 'phone',
                                              'placeholder': 'Contact No'}))
    address = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control input-glass', 'id': 'address',
                                              'placeholder': 'Address'}))
    restaurant_image = forms.ImageField()

我的观看代码是:

def updatedetails(request):
    current_user = request.user.id
    rest = RestaurantProfile.objects.get(username=current_user)
    rid = rest.id
    if request.method == 'POST':
        print("fas")
        form = UpdateDetailsForm(request.POST, request.FILES)
        print(request.FILES)

        if form.is_valid():
            data = form.cleaned_data
            print(data)
            phone = data["phone"]
            address = data["address"]
            image = data["restaurant_image"]
            RestaurantProfile.objects.filter(id=rid).update(phone=phone, address=address, restaurant_image=request.FILES['restaurant_image'])
            return redirect('dashboard')
        else:
            print(form.errors)
    else:
        form = UpdateDetailsForm()

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

在我的setting.py中,我添加了:

# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

在url.py中,我添加了:

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

1 个答案:

答案 0 :(得分:1)

在您的情况下,您需要保存文件手册,如Django file upload doc

或简单的方式

DELIMITER $$ CREATE TRIGGER pic_pic AFTER INSERT ON pp_change FOR EACH ROW BEGIN BEGIN UPDATE profile SET profile_pix = pp_change.pic FROM Inserted pp_change WHERE profile.email = pp_change.email INSERT INTO photos (email,pic,wardrobe,upload_type,pic_view,up_user_id,country,time_group,fpage) SELECT (email,pic,wardrobe,upload_type,pic_view,user_id,country,time_group,fpage) from pp_change END$$ DELIMITER ;

    class UpdateDetailsForm(forms.ModelForm):
        class Meta:
         model = RestaurantProfile
         fields = ('phone', 'address', 'restaurant_image', )

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM Inserted pp_change

    form = UpdateDetailsForm(request.POST, request.FILES)

    if form.is_valid():
        form.save()