簡體   English   中英

Django OneToOne配置文件/用戶關系未保存

[英]Django OneToOne Profile/User relationship not saving

我試圖設置一個Django博客應用程序,以使用從User到Profile模型的一對一關系,以捕獲模式信息,而不是默認的Django User模型。 我遇到的問題是我的個人資料模型沒有保存,即使成功注冊了用戶,我的個人資料表仍保持不變。 這是我的看法:

@transaction.atomic
def profile_new(request):
    if request.method == "POST":
        user_form = UserForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)
            profile = profile_form.save(commit=False)
            user.username = user.email
            user.set_password(user.password)
            user.save()
            profile.user = user
            profile.save()
            return redirect('profile_detail', pk=user.pk)
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        user_form = UserForm()
        profile_form = ProfileForm()
    return render(request, 'accounts/update.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

非常簡單,運行完全沒有錯誤,它實際上從未保存過Profile對象。 繼承人的形式:

from django import forms
from .models import User, Profile

class UserForm(forms.ModelForm):
    """confirm_password = forms.CharField()"""
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'password')

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('bio', 'birth_date', 'avatar', 'location')

以及Profile的模型:

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


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    bio = models.TextField(max_length=500, blank=True)
    avatar = models.ImageField(upload_to = 'avatars/', default = 'avatars/default.jpg')
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

有誰看到個人資料無法保存的任何原因? 我的第二個問題是:保存和哈希該密碼的正確方法是什么? 我已經知道我可以在表單中添加一個臨時的“確認密碼”字段,但是我不是如何散列和保存我獲得的密碼。

請嘗試以下代碼:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True,null=True)

我認為如果user字段為空,您的個人資料表將無法保存新記錄!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM