Django中扩展模型的问题

时间:2018-03-20 09:24:08

标签: python django django-models django-forms

我目前正在开发用于用户身份验证的webapp。用户应该编辑他的属性,但是当我尝试扩展用户模型时,它无法显示属性。

这是我的models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user = models.OneToOneField(User)
    salutation = models.CharField(max_length=100, default='')
    title = models.CharField(max_length=100, default='')

@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 UserForm(forms.ModelForm): 
    class Meta:
        model = User
        fields = (
            'first_name',
            'last_name',
            'email',
        )

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = (
          'title',
     )

这是模板:

<form method="post">
    {% csrf_token %}
    {{ user_form.as_p }}
    {{ profile_form.as_p }}

配置文件:form.as_p没有做任何事情,当我尝试保存更改时,它也没有做任何事情。显然我错过了一些东西,但我找不到它。

1 个答案:

答案 0 :(得分:3)

您无法将两个单独的词典传递给render。您需要一个包含两个元素的字典:

args = {'user_form': user_form, 'profile_form': profile_form}
return render(request, 'accounts/edit_profile.html', args)