我是新开发人员,我想知道您是否可以帮助我,通过编辑表单更新 User / UserProfile 的值。
我一开始并不知道,但现在我知道我可以扩展(默认) 用户 模型并避免创建新模型 UserProfile 用于配置文件目的并使事情更简单(例如使用通用视图)。
由于我还在学习,所以我决定尝试一种解决方法,让自己思考,而不是要求完整的解决方案。
我已经在这里和Django的官方文档中查找了类似的问题,但由于我没有遵循特定的配方,我无法找到正确修复它的东西。
到目前为止我所得到的:
models.py
class UserProfile(models.Model):
GENDER_CHOICES = (
('M', 'Masculino'),
('F', 'Feminino')
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_image = models.ImageField(upload_to='uploads/', blank=True, null=True)
gender = models.CharField(max_length=40, blank=True, null=True, choices=GENDER_CHOICES)
birthday = models.DateField(blank=True, null=True)
address = models.TextField(max_length=300, blank=True, null=True)
city = models.TextField(max_length=50, blank=True, null=True)
country = models.TextField(max_length=50, blank=True, null=True)
def __str__(self):
return str(self.id)
forms.py
class CustomUserForm(ModelForm):
class Meta:
model = User
fields = [
'username', 'id', 'first_name', 'last_name', 'email', 'last_login', 'date_joined'
]
widgets = {
'username': forms.TextInput(attrs={'class': 'form-control'}),
'id': forms.TextInput(attrs={'class': 'form-control', 'readonly': 'readonly'}),
'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Insira seu nome'}),
'last_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Insira seu sobrenome'}),
'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Insira seu email. Ex: seuemail@gmail.com'}),
'last_login': forms.DateInput(attrs={'class': 'form-control-plaintext rdonly', 'readonly': 'readonly'}),
'date_joined': forms.DateInput(attrs={'class': 'form-control-plaintext rdonly', 'readonly': 'readonly'}),
}
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = [
'profile_image', 'gender', 'birthday', 'address', 'city', 'country'
]
widgets = {
'profile_image': forms.ClearableFileInput(attrs={'class': ''}),
'gender': forms.Select(attrs={'class': 'form-control'}),
'birthday': forms.DateInput(attrs={'class': 'form-control'}),
'address': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Insira seu endereço completo'}),
'city': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Insira sua cidade. Ex: Recife-PE'}),
'country': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Informe o país em que vive'}),
}
views.py
class Profile(View):
def get(self, request, *args, **kwargs):
submitted = False
if request.user.is_authenticated():
# Getting the Target objects in the DB
targetuserprofile = UserProfile.objects.get(user=request.user)
# Instanciating forms and passing current values
profile_form = UserProfileForm(instance=targetuserprofile)
user_form = CustomUserForm(instance=request.user)
user_form.id = request.user.id
else:
return HttpResponseRedirect('/login/?next=/')
if 'submitted' in request.GET:
submitted = True
context = {
'user_form': user_form,
'profile_form': profile_form,
'submitted': submitted
}
return render(request, "registration/profile.html", context)
def post(self, request, *args, **kwargs):
submitted = False
# Creating new forms
profileform_formclass = UserProfileForm
userform_formclass = CustomUserForm
# Getting the values passed throught POST method
profile_form = profileform_formclass(request.POST, request.FILES)
user_form = userform_formclass(request.POST)
# Getting the Target objects in the DB
targetuserprofile = UserProfile.objects.filter(user=request.user)
targetuser = request.user
# Validating forms and saving
if profile_form.is_valid() & user_form.is_valid():
profile = profile_form.save(commit=False)
usr = user_form.save(commit=False)
targetuserprofile.user = targetuser
targetuserprofile.profile_image = profile.profile_image
targetuserprofile.gender = profile.gender
targetuserprofile.birthday = profile.birthday
targetuserprofile.address = profile.address
targetuserprofile.city = profile.city
targetuserprofile.country = profile.country
targetuserprofile.save()
targetuser.first_name = usr.first_name
targetuser.last_name = usr.last_name
targetuser.email = usr.email
targetuser.save()
else:
return HttpResponse("Erro")
submitted = True
context = {
'submitted': submitted
}
return render(request, "registration/profile.html", context)
profile.html (仅限相关部分)
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ profile_form.profile_image }}
{{ user_form.first_name }}
{{ user_form.last_name }}
{{ user_form.email }}
{{ profile_form.gender }}
{{ profile_form.birthday }}
<label class="profile_readonly"></label>
{{ user_form.id }}
<label class="profile_readonly"></label>
{{ user_form.last_login }}
<label class="profile_readonly"></label>
{{ user_form.date_joined }}
{{ profile_form.address }}
{{ profile_form.city }}
{{ profile_form.country }}
<input class="btn btn-primary" type="submit" value="Salvar" />
</form>
获取 方法( views.py )工作正常,以显示当前 User / UserProfile 值,但 帖子 的值不会更新值。也许是我在验证它时做错了,因为我得到了错误&#34;来自 else 语句的消息。关于如何正确更新 User / UserProfile 的任何想法?