本文介绍了我无法在Django Views.py中同时更新两个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在


但是我没有找到合适的解决方案。这就是为什么我要对此问题进行类似的处理。


我有 pages.views.py

 从django.shortcuts导入渲染,重定向
从.forms导入CreateUserForm
从accounts.models导入帐户
从django.contrib导入消息

def signupPage(request):
if request.user.is_authenticated:
return redirect('/')
else:
form = CreateUserForm()
if request.method =='POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()

#专注于此行
Account.objects.create(user = user)

messages.success(请求,注册成功。现在,您可以登录。)
return redirect('login')
else:
messages.warning(request,'注册失败。请重试。')
context = {'form':form}
返回render(request,'signup.html',上下文)

也,我有 accounts.models.py


从django.db导入模型
从django.contrib .auth.models导入用户

类Account(models.Model):

user = models.ForeignKey(User,null = True,on_delete = models.CASCADE)

#此字段用于更新Django模型用户
first_name = models.CharField(max_length = 30,null = True,blank = False)
last_name = models.CharField(max_length = 30,null = True,blank = False)
email = models.EmailField(max_length = 30,null = True,blank = True)

profile_photo = models.ImageField(upload_to =' profile',null = True)
mobile_number = models.PositiveBigIntegerField(null = True)
date_of_birth = models.DateField(auto_now_add = False,auto_now = False,null = True)
邮政编码=模型.IntegerField(null = True)
地址= models.CharField(max_leng th = 225,null = True)
网站= models.URLField(max_length = 100,null = True)
bio = models.CharField(max_length = 225,null = True)

Accounts.view.py 中:

  from django.shortcuts导入渲染,重定向
从.forms导入AccountForm
从.models导入帐户
从pages.forms导入CreateUserForm
从django.contrib导入消息$来自django.contrib.auth.models的b $ b导入用户

首先,我尝试了此操作:

  def profileSettingsPage(request,pid):
user = User.objects.get(id = pid)
形式= AccountForm(instance = user )
if request.method =='POST':
form = AccountForm(request.POST,request.FILES,instance = user)
if form.is_valid():

user.first_name = form.cleaned_data.get('first_name')
user.last_name = form.cleaned_data.get('last_name')
user.email = for m.cleaned_data.get('email')
user.save()

form.save()

messages.success(请求,已保存配置文件。 ')
else:
messages.warning(request,'容易保存配置文件')
context = {'form':form}
return render(request,'profile- settings.html',上下文)

但这只会保存用户模型,而不是AccountForm。


然后替换 user = request.user 。再次,它仅保存用户模型,而不保存AccountForm。


再次,我替换 user = Account.objects.get(id = pid)。然后,我遇到错误 DoesNotExist:帐户匹配查询不存在。


即使我尝试了此

  def profileSettingsPage(request,pid):
形式= AccountForm()
如果request.method =='POST':
形式= AccountForm(request.POST,请求.FILES)
if form.is_valid():
form.save()
用户= User.objects.get(id = pid)
user.first_name = form.cleaned_data .get('first_name')
user.last_name = form.cleaned_data.get('last_name')
user.email = form.cleaned_data.get('email')
user.save ()
messages.success(请求,配置文件已保存。)
其他:
messages.warning(请求,易于保存的配置文件)
context = {'form ':form}
返回render(request,'profile-settings.html',上下文)

保存这两个模型,但问题是它创建了一个新模型并保存e Account模式的ForeignKey中的空值,其他字段保持原样,并使用这些值保存了User模型。


现在,我的问题是我该如何同时更新在pages.views.py和Django User模型中创建的Account模型?


我对传递实例值感到困惑。 我和每个人都一样吗?还是我做错了?

解决方案
  class Account(模型。 Model):

user = models.OneToOneField(User,null = True,on_delete = models.CASCADE)

#此字段用于更新Django模型用户
first_name = models.CharField(max_length = 30,null = True,blank = False)
last_name = models.CharField(max_length = 30,null = True,blank = False)
电子邮件=模型。 EmailField(max_length = 30,null = True,blank = True)

profile_photo = models.ImageField(upload_to ='profile',null = True)
mobile_number = models.PositiveBigIntegerField(null = True)
date_of_birth = models.DateField(auto_now_add = False,auto_now = False,null = True)
zip_code = models.IntegerField(null = True)
地址= models.CharField(max_length = 225,null = True)
网站= models.URLField(max_length = 100,null = True)
bio = models.CharField(max_length = 225,null = True)

def profileSettingsP年龄(request,pid):
形式= AccountForm()
如果request.method =='POST':
用户= User.objects.get(id = pid)
user.first_name = request.POST.get('first_name')
user.last_name = request.POST.get('last_name')
user.email = request.POST.get('email')
user.save()
实例= Account.objects.get(user = user)
形式= AccountForm(request.POST,request.FILES,instance = instance)
如果form.is_valid():
form.save()
messages.success(请求,配置文件已保存。)
其他:
messages.warning(请求,易于保存的配置文件')
context = {'form':form}
return render(request,'profile-settings.html',context)


I already ask questions related to this atHow can I update first_name, last_name & email of Django model User and update other field in separate models

But I'm not getting a proper solution. That's why I make this question similar to that one.

I have pages.views.py:

from django.shortcuts import render, redirect
from .forms import CreateUserForm
from accounts.models import Account
from django.contrib import messages

def signupPage(request):
    if request.user.is_authenticated:
        return redirect('/')
    else:
        form = CreateUserForm()
        if request.method == 'POST':
            form = CreateUserForm(request.POST)
            if form.is_valid():
                user = form.save()

                # focus on this line
                Account.objects.create(user=user)

                messages.success(request, 'Signup success. Now, you can login.')
                return redirect('login')
            else:
                messages.warning(request, 'Signup failed. Please, try again.')
        context = {'form':form}
        return render(request, 'signup.html', context)

Also, I have accounts.models.py:

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

class Account(models.Model):

    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)

    # This field is used for to update django model User
    first_name=models.CharField(max_length=30, null=True, blank=False)
    last_name=models.CharField(max_length=30, null=True, blank=False)
    email = models.EmailField(max_length=30, null=True, blank=True)

    profile_photo = models.ImageField(upload_to='profile', null=True)
    mobile_number = models.PositiveBigIntegerField(null=True)
    date_of_birth = models.DateField(auto_now_add=False, auto_now=False, null= True)
    zip_code = models.IntegerField(null=True)
    address = models.CharField(max_length=225, null=True)
    website = models.URLField(max_length=100, null=True)
    bio = models.CharField(max_length=225, null=True)

In Accounts.view.py:

from django.shortcuts import render, redirect
from .forms import AccountForm
from .models import Account
from pages.forms import CreateUserForm
from django.contrib import messages
from django.contrib.auth.models import User

First of all I tried this:

def profileSettingsPage(request, pid):
    user= User.objects.get(id=pid)
    form = AccountForm(instance=user)
    if request.method == 'POST':
        form = AccountForm(request.POST, request.FILES, instance=user)
        if form.is_valid():

            user.first_name = form.cleaned_data.get('first_name')
            user.last_name = form.cleaned_data.get('last_name')
            user.email = form.cleaned_data.get('email')
            user.save()

            form.save()

            messages.success(request, 'Profile saved.')
        else:
            messages.warning(request, 'Faile to saved profile')
    context = {'form':form}
    return render(request, 'profile-settings.html', context)

But It will only save the User model, not AccountForm.

Then I replace user = request.user. Again, it save the user model only, not AccountForm.

Again, I replace user = Account.objects.get(id=pid). Then, I faced error DoesNotExist: Account matching query does not exist.

Even I tried this

def profileSettingsPage(request, pid):
    form = AccountForm()
    if request.method == 'POST':
        form = AccountForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            user = User.objects.get(id=pid)
            user.first_name = form.cleaned_data.get('first_name')
            user.last_name = form.cleaned_data.get('last_name')
            user.email = form.cleaned_data.get('email')
            user.save()
            messages.success(request, 'Profile saved.')
        else:
            messages.warning(request, 'Faile to saved profile')
    context = {'form':form}
    return render(request, 'profile-settings.html', context)

It saves both the models, but the problem was it created a new one and save the null value in the ForeignKey of Account model, other fields saved as it is, and also saved the User model with those values.

Now, my question is how can I update the Account model that I created in pages.views.py and Django User model at the same times ?

I get confused on passing instance value. Did I did the same as everyone does? or Did I do some mistake ?

解决方案
class Account(models.Model):

    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)

    # This field is used for to update django model User
    first_name=models.CharField(max_length=30, null=True, blank=False)
    last_name=models.CharField(max_length=30, null=True, blank=False)
    email = models.EmailField(max_length=30, null=True, blank=True)

    profile_photo = models.ImageField(upload_to='profile', null=True)
    mobile_number = models.PositiveBigIntegerField(null=True)
    date_of_birth = models.DateField(auto_now_add=False, auto_now=False, null= True)
    zip_code = models.IntegerField(null=True)
    address = models.CharField(max_length=225, null=True)
    website = models.URLField(max_length=100, null=True)
    bio = models.CharField(max_length=225, null=True)

def profileSettingsPage(request, pid):
    form = AccountForm()
    if request.method == 'POST':
        user = User.objects.get(id=pid)
        user.first_name = request.POST.get('first_name')
        user.last_name = request.POST.get('last_name')
        user.email = request.POST.get('email')
        user.save()
        instance = Account.objects.get(user=user)
        form = AccountForm(request.POST, request.FILES,instance=instance)
        if form.is_valid():
            form.save()
            messages.success(request, 'Profile saved.')
        else:
            messages.warning(request, 'Faile to saved profile')
    context = {'form':form}
    return render(request, 'profile-settings.html', context)

这篇关于我无法在Django Views.py中同时更新两个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:56