我在Django 2中有一个扩展的用户模型,我想为其创建一个更新表单。
我在django.contrib.auth.models.User
和我的自定义模型之间使用了一对一的关系。
扩展的用户模型为:
class Employer(models.Model):
employer_id = models.AutoField(primary_key=True)
address = models.CharField(max_length=400)
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
profile_pic = models.ImageField(upload_to='uploads/profile/%Y/%m/%d/', blank=True)
@receiver(post_save, sender=User)
def save_user_employer(sender, instance, created, **kwargs):
if not created:
try:
instance.employer.save()
except Employer.DoesNotExist:
pass
我的表单类是:
class EmployerForm(UserCreationForm):
address = forms.CharField(max_length=400)
profile_pic = forms.ImageField(required=False)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'profile_pic')
在我的视图类中:
class EditEmployerView(UpdateView):
template_name = 'registration/employer.html'
form_class = EmployerForm()
success_url = 'dashboard'
def get_object(self, query_set=None):
return self.request.user
在模板中,我使用widget-tweaks
自动呈现表单:
{% for field in form.visible_fields %}
{% render_field field class="form-control" placeholder=field.label %}
{% endfor%}
问题在于,在模板表单中,只有“用户”字段填充了数据,而“雇主”字段为空。
如何使表单填充User和Employer类的现有数据?