[英]Image not uploading in Django Model
I am able to update the image of each user's profile picture.我能够更新每个用户的个人资料图片的图像。 But not through the code.
但不是通过代码。 Though it doesn't give me any error.
虽然它没有给我任何错误。
u_form = For changing the username. u_form = 用于更改用户名。 p_form = For changing the picture in their profile.
p_form = 用于更改其个人资料中的图片。
NOTE: Profile has one to one relation with the Profile model.注意:Profile 与 Profile 模型是一对一的关系。
settings.py file section: settings.py文件部分:
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
models.py for Profile model:用于 Profile 模型的models.py :
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpeg', upload_to='profile_pics')
status = models.TextField(max_length='200')
def __str__(self):
return self.user.username
forms.py for the same: forms.py 相同:
class ProfileUpdate(forms.ModelForm):
class Meta:
model = Profile
fields = ['image',]
Main views.py file:主要的views.py文件:
.
.
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm as uc
from django.contrib.auth.forms import AuthenticationForm as af
.
.
@login_required(login_url='/login')
def update_profile(request):
user = request.user
if request.method == 'POST':
u_form = UserUpdate(request.POST, instance=user)
p_form = ProfileUpdate(request.POST, request.FILES, instance=user)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, 'The profile has been updated.')
return redirect('/profile')
else:
#instance: to get pre-filled data of user
u_form = UserUpdate(instance=user)
p_form = ProfileUpdate(instance=user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'update_profile.html', context)
HTML form "update_profile.html": HTML 表单“update_profile.html”:
<form action="{% url 'update_profile' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ u_form }}
{{ p_form }}
<button type="submit">submit</button>
</form>
尝试这个:
p_form = ProfileUpdate(request.POST, request.FILES, instance=user.profile)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.