0

我想通過django做一個簡單的註冊/登錄頁面。 我已經使用UserCreationForm並使用模型UserProfile來擴展用戶模型。 我想檢索從用戶登錄後在我的主頁上的表單發佈的數據。 我是django的新手,所以我將不勝感激。 在此先感謝如何從擴展用戶模型檢索數據

forms.py

from django import forms 
from django.contrib.auth.forms import UserCreationForm 
from django.contrib.auth.models import User 
from mysite.core.models import UserProfile 
from django.db import models 

class SignUpForm(UserCreationForm): 
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') 
    department = forms.CharField(max_length=30) 
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') 
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') 

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

    def save(self, commit=True): 
     # Save the provided password in hashed format 
     user = super(SignUpForm, self).save(commit=False) 
     user_profile = UserProfile(user=user, department=self.cleaned_data['department']) 
     user.save() 
     user_profile.save() 
     return user, user_profile 

views.py

from django.contrib.auth.decorators import login_required 
from django.contrib.auth import login, authenticate 
from django.shortcuts import render, redirect 
from mysite.core.forms import SignUpForm 

@login_required 
def home(request): 
    return render(request, 'home.html') 

def signup(request): 
    if request.method == 'POST': 
     form = SignUpForm(request.POST) 
     if form.is_valid(): 
      user,user_profile = form.save(commit=False) 
      username = user.cleaned_data.get('username') 
      raw_password = user.cleaned_data.get('password1') 
      user = authenticate(username=username, password=raw_password) 
      login(request, user) 
      return redirect('home') 
    else: 
     form = SignUpForm() 
    return render(request, 'signup.html', {'form': form}) 

models.py

from django.db import models 
from django.contrib.auth.models import User 
class UserProfile(models.Model): 
    user = models.ForeignKey(User, on_delete=models.CASCADE,unique=True) 
    department = models.CharField(max_length=500, blank=True) 

home.html的模板:

{% extends 'base.html' %} 
{% block content %} 
<h2>Welcome, <small>{{ user.username }}</small>!</h2> 
<p>Your email address: {{ user.email }}</p> 
<p>Department: {{ user_profile.department }}</p> 
{% endblock %} 

我可以打印用戶名和電子郵件,但部門將空。

回答

2

首先,你有錯誤的關係。 User和UserProfile之間有一對一的關係;用戶只能有一個配置文件,配置文件只能屬於一個用戶。現在你擁有它的方式,用戶可以有許多配置文件,這是沒有道理的。

您應該用OneToOneField替換ForeignKey。

完成此操作後,您將可以通過以下關係訪問配置文件數據:user.userprofile.department等等。

+0

非常感謝:) –