我在djano-web fromework上做了一个项目。在提交django表单时会发生一些奇怪的事情。即使表单有效,所有内容都会在db中接受 配置文件图像 。
views.py:
class EmployeeEditProfile(CommonViewMixin, View):
template_name = 'edit_employee.html'
authorization = [authorize_employee]
user_personal_form = UserPersonalDetailForm
user_details_form = OrganisationUserDetailsForm
user_profile_form = OrganisationUserProfileDetailsForm
@transaction.atomic()
def non_ajax_post(self, request, *args, **kwargs):
user_personal_form = self.user_personal_form(request.POST, instance=request.user)
user_details_form = self.user_details_form(request.POST, instance=request.user.organisation_user.user_details)
user_profile_form = self.user_profile_form(request.POST,request.FILES, instance=request.user.organisation_user)
if user_details_form.is_valid() and user_personal_form.is_valid() and user_profile_form.is_valid():
user_personal_form.save()
user_detail = user_details_form.save()
request.user.organisation_user.user_details = user_detail
request.user.organisation_user.save()
user_profile_form.save()
request.session['user_form_saved'] = True
return HttpResponseRedirect(request.path)
else:
print user_details_form.errors
print user_personal_form.errors
context = kwargs
context.update({'user_personal_form': user_personal_form, 'user_details_form': user_details_form, 'user_profile_form':user_profile_form})
return self.response_class(template='edit_employee.html',request=request,
context=context)
UserProfileDetails的模型:models.py
class OrganisationUserProfileDetails(models.Model):
profile_image = models.ImageField(upload_to='profile_images', null=True, blank=True, default='default_images/profile_pic')
organisation_user = models.OneToOneField(OrganisationUser, related_name='profile_details')
forms.py:
class OrganisationUserProfileDetailsForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(OrganisationUserProfileDetailsForm, self).__init__(*args, **kwargs)
self.fields['profile_image'].label_from_instance = lambda obj: '%s' %(obj.name)
class Meta:
model = OrganisationUserProfileDetails
fields = ('profile_image',)
任何帮助都会很明显。
答案 0 :(得分:0)
我认为您还需要存储organisation_user
。
试试这个:
newproject = user_profile_form.save(commit=False)
newproject.profile_image = request.FILES['profile_image']
newproject.organisation_user = request.user.organisation_user
newproject.save()