在django中更新用户及其用户个人资料

时间:2019-01-09 08:14:26

标签: python django

如何将用户字段数据和用户配置文件数据绑定到视图上的模型表单,当我使用instance = user时,我只能将用户数据呈现给表单,但不能在实例上呈现用户配置文件的任何数据= profile,我需要将所有用户及其个人资料呈现为表单。

models.py

class User(AbstractUser):
is_supervisor = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)


class Supervisor(models.Model):
user = models.OneToOneField('User', on_delete=models.CASCADE, primary_key=True, related_name='supervisor')
su_mobile_number = models.CharField(max_length=200)

view.py

def supervisor_update(request, user_id):
# user = get_object_or_404(User, pk=user_id)
user = get_object_or_404(User, pk=user_id)
profile = get_object_or_404(Supervisor, pk=user_id)
if request.method == 'POST':
    form = SupervisorSignUpForm(request.POST, instance=user)
else:
    form = SupervisorSignUpForm(instance=user)
return save_user_form(request, form, 'partials/partial_supervisor_update.html')

form.py

class SupervisorSignUpForm(UserCreationForm):
su_mobile_number = forms.CharField(label="Mobile Number")

class Meta(UserCreationForm.Meta):
    model = User
    fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name')

supervisor_update.html

{% load crispy_forms_tags %}
<form method="post" action="{% url 'supervisor_update' form.instance.pk %}" class="js-supervisor-update-form">
{% csrf_token %}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
  <span aria-hidden="true">&times;</span>
  </button>
  <h4 class="modal-title">Update Supervisor</h4>
  </div>
  <div class="modal-body">
  {% include 'partials/form_messages.html' %}



    {{ form.username|as_crispy_field }}

    {{ form.email|as_crispy_field }}


    {{ form.first_name|as_crispy_field }}

    {{ form.last_name|as_crispy_field }}

    {{ form.su_mobile_number|as_crispy_field }}


    </div>
    <div class="modal-footer">
    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Update Supervisor</button>
    </div>
    </form>

1 个答案:

答案 0 :(得分:1)

设置与用户实例一起传入的额外字段应该起作用


    initial = {'su_mobile_number': profile.su_mobile_number}
    form = SupervisorSignUpForm(instance=user, initial=initial)

或者,如果您不想手动创建字典,则可以使用model_to_dict


    from django.forms.models import model_to_dict
    initial = model_to_dict(profile, exclude=['user'])
    form = SupervisorSignUpForm(instance=user, initial=initial)

在视图的顶部,您还假设用户和主管具有相同的ID(事实并非如此),您可以这样做


    user = user = get_object_or_404(User, pk=user_id)
    profile = user.supervisor
    if not profile:
        raise Http404