我有一个用户的个人资料模型,其中包含“生物”和“封面”等字段,代表有关用户个人资料的常规信息等。 我希望用户可以编辑这两件事。我做了从urls.py到forms.py到views.py到模板等的所有内容,看起来我可以提交数据,它看起来像验证但数据没有被保存..我不知道如何..
这是我的文件,我已经包含了更多的代码,只是为了看看其他地方的代码是否有问题。
请注意,无法使用的代码是名称
中包含“general”的代码urls.py
from django.conf.urls import include, url
from . import views
app_name = 'profili'
urlpatterns = [
#profile
url(r'^$', views.ProfilePage, name='profile'),
url(r'^edit/$', views.EditProfile, name='edit_profile'),
url(r'^edit/general/$', views.EditGeneralProfile, name='edit_general_profile'),
url(r'^edit/password$', views.EditPassword, name='edit_password'),
url(r'^edit/delete/$', views.DeleteProfile, name='delete_profile'),
]
views.py
def EditProfile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, request.FILES, instance=request.user)
if form.is_valid():
form.save()
return redirect('/profile')
else:
form = EditProfileForm(instance=request.user)
formpw = PasswordChangeForm(user=request.user)
generalform = EditGeneralProfileForm(instance=request.user)
args = {
'form': form,
'formpw': formpw,
'generalform': generalform,
}
return render(request, 'profili/editprofile.html', args)
@login_required
def EditGeneralProfile(request):
generalform = EditGeneralProfileForm(request.POST, request.FILES, instance=request.user)
if generalform.is_valid():
generalform.save()
return redirect('/profile')
else:
print('THIS IS NOT WOOORRKIINNGGG')
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followall = models.ManyToManyField(User, related_name='followfriend')
bio = models.TextField(max_length=100, default='', blank=True)
cover = models.FileField(blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
forms.py
class EditGeneralProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('bio', 'cover')
表单实际出现在GET请求中的模板
<form class="form-self general-form" method="post" action="{% url 'profili:edit_general_profile' %}" enctype="multipart/form-data">
{% csrf_token %}
{% for item in generalform %}
<div class="full-part">
<div class="label-par">
<span class="label-part">{{ item.label }}:</span>
</div>
<div class="original-part">{{ item }}</div>
</div>
{% endfor %}
<div class="full-part-btn">
<button type="submit" class="fpartbtn">Save</button>
</div>
</form>
答案 0 :(得分:0)
这是Profile模型的一个表单,因此您应该将其作为实例传递。
generalform = EditGeneralProfileForm(request.POST, request.FILES, instance=request.user.profile)