Reputation: 743
I am trying to upload an image via the ImageField. I am getting http 200, but the image is not getting saved.
My model is:
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)
My form is:
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()
My view code is:
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})
In my setting.py, I have added:
# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In the url.py, I have added:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Upvotes: 1
Views: 2814
Reputation: 148
In your case you need save file manual like this Django file upload doc
or simple way
form.py
class UpdateDetailsForm(forms.ModelForm): class Meta: model = RestaurantProfile fields = ('phone', 'address', 'restaurant_image', )
view.py
form = UpdateDetailsForm(request.POST, request.FILES) if form.is_valid(): form.save()
Upvotes: 1