First, let's talk about how to upload avatars when adding users I upload files here with element-ui Inside upload Components
class User(models.Model):
''' User table '''
email=models.CharField(max_length=255,unique=True)
password=models.CharField(max_length=255)
intorduction=models.CharField(' Personal profile ',max_length=255,null=True)
phone=models.CharField(' cell-phone number ',max_length=255,null=True)
# add head_img This field is used to save the avatar
head_img=models.FileField(' Head portrait ',null=True,max_length=255)
role_id=models.ManyToManyField(Role)
stay settings Stick on the following code
To configure MEDIA_ROOT To generate files automatically
To configure MEDIA_URL To allow the client to directly access Media Data in , Be similar to STATIC_URL
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
from django.contrib import admin
from django.urls import path, re_path,include
from django.views.static import serve
from django_mianshibaodian import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('RBACapp.urls')),
# Mainly with media start , You can write anything in the back
re_path(r'media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT})
]
example : there head_img It's the picture you sent You can write your corresponding data
class putHeadImg(View):
def post(self,res):
file = res.FILES.get("file")
User.objects.create(email='email',head_img=file,password=123)
return JsonResponse({'message':' Modify the head image !'})
We can go right through ip+media+ picture name that will do
example :
Here we say to modify the file The generated file can only be found in create Method to generate changes, the image will not be generated automatically , So I used open Method to write an image
Here I have a problem upload The transmitted data is not only the binary of the picture, but also the file name. There is no good way to deal with some other things
Then I found out file = res.FILES.get("file") This is not just the file name !!!!!
We can use file.file.read() We can get the binary of the corresponding image and save it directly
class putHeadImg(View):
def post(self,res):
file = res.FILES.get("file")
f=open('./media/'+username+'.jpg','wb+')
f.write(file.file.read())
f.close()
return JsonResponse({'message':' Modify the head image !'})
The pictures stored by my user name will be replaced after modification OK It's over here !! Hopefully that helped !