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

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

问题描述:

我延长了默认的用户模型,这样Django的扩展用户模型中没有扩展属性

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

我对此不完全确定,但您的模型看起来不正确。您应该使用AbstractUser而不是User。请阅读此:https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#substitution-a-custom-user-model – 1GDST

+0

UserForm中,模型应该是配置文件 – itzMEonTV

我认为你正在试图访问该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() 

确保您从表单更新用户的个人资料数据

+0

由于@itzmeontv说,也取代 –