Django扩展用户模型没有扩展属性

时间:2016-11-16 17:04:54

标签: python django django-views

我正在以这种方式扩展默认用户模型

models.py

from django.db import models
from django.contrib.auth.models import User

class Profile(User):
    city = models.CharField(max_length = 60)
    company = models.CharField(max_length = 100)

    def __str__(self):
        return self.username

我正在使用以下视图注册用户。

class ProfileFormView(View):
    form_class = UserForm
    template_name = 'register.html'

    # Display empty form
    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    # Process user data and add to DB.
    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            user = form.save(commit = False)

            # clean form data.
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.city = form.cleaned_data['city']
            user.company = form.cleaned_data['company']
            user.set_password(password)
            user.save()

            # returns User object if credentials are correct
            user = authenticate(username= username, password = password)

            if user is not None:

                if user.is_active:
                    login(request, user)

                    return render(request, 'profile.html', {})

        return render(request, self.template_name, {'form': form})

正如您所看到的,我在注册页面上按下提交后重定向到profile.html,我在表单的操作中调用的视图函数如下所示

def home(request):
    all_users = Profile.objects.all()
    city = request.user.city # this line throws error
    return render(request, 'profile.html', {'city': city,'login_user': request.user, 'all_users': all_users})

Exception Value: 'User' object has no attribute 'city'

但我无法访问城市的用户错误被抛出上面标记的行。我究竟做错了什么。谢谢

1 个答案:

答案 0 :(得分:0)

我认为您应该尝试访问User.city属性,而应该通过User.profile.city进行操作。

city = request.user.city # this line throws error

替换为:

# Check if the user has a profile
if hasattr(request.user, 'profile'):
    city = request.user.profile.city
# Otherwise, city is None (Or throw an Exception)
else:
    city = None

修改

正如@itzmeontv所说,也取代:

# clean form data.
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.city = form.cleaned_data['city']
user.company = form.cleaned_data['company']
user.set_password(password)
user.save()

使用:

# Clean user form data.
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save() 

# Update or create the user's profile
profile, _ = Profile.objects.get_or_create(id=user.pk)
profile.__dict__.update(user.__dict__)
profile.city = form.cleaned_data['city']
profile.company = form.cleaned_data['company']
profile.save()

确保您从表单

更新用户的个人资料数据