我有一个模型表单来更新用户配置文件,除了图像之外,一切都正确保存。如果我使用admin它会更新,但是当我使用我的表单时它只是作为默认的配置文件图像。
这是我的表格:
class EditProfileForm(forms.ModelForm):
birth_date = forms.DateField(label='birth_date', input_formats=['%Y-%m-%d'])
class Meta:
model = UserProfile
fields = (
"image",
"bio",
"location",
"birth_date",
)
这是我的模型:
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
image = models.ImageField(upload_to='profile_image', blank=True)
def __str__(self):
return self.user.username
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
这是我的观点:
def edit_profile(request):
instance = get_object_or_404(UserProfile, user=request.user)
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect('/')
else:
form = EditProfileForm(instance=request.user)
return render(request, 'edit_profile.html', {'form': form})
这是我的HTML:
{% extends 'base.html' %}
{% block content %}
<h1>Edit Profile</h1>
<form method='POST' action=''>{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-outline-success">Save</button>
</form>
</body>
{% endblock %}
对于文件上传,您需要指定表单enctype:
<form method='POST' action='' enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-outline-success">Save</button>
</form>
您应该将请求的文件传递给视图中的表单实例:
form = EditProfileForm(request.POST, request.FILES, instance=instance)
查看此doc了解详情。