如何在POST请求之后或之前动态插入外键Python Django

问题描述

我正在尝试在运行时动态分配外键。

我希望每个登录用户都可以将新联系人添加到自己的列表中。 我知道我需要使用具有多对一关系的外键,但是我不知道该如何实现。

主要目标是分配添加到已登录用户的新联系人并立即添加他,我需要在他们之间进行连接。

许多NewContactInfo实例应该与一个UserProfileInfo

相关

model.py

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

class UserProfileInfo(models.Model):

user=models.OnetoOneField(User,on_delete=models.CASCADE,blank=True,null=True,editable=False)


#model calss to add adinonal info that the default user does not have
#for ex: llike titles

Titles = (
    ("1","Mr"),("2","Mrs"),("3","Miss"),("4","Dr"),("5","Prof"))

Title=models.CharField(max_length=1,choices=Titles,blank=False,default=Titles[0])
first_name=models.CharField(max_length=128,blank=False)
last_name=models.CharField(max_length=128,blank=False)



def __str__(self):
    return self.user.username

class newContactInfo(models.Model):
    Titles = (
        ("1","Prof"))
    Title = models.CharField(max_length=1,default=Titles[0])
    first_name = models.CharField(max_length=128,blank=False)
    last_name = models.CharField(max_length=128,blank=False)
    Phone=models.IntegerField(default=0)
    user_profile_info = models.ForeignKey(UserProfileInfo,editable=False)

forms.py

from django import forms
from first_app.models import UserProfileInfo,Login,newContactInfo
from django.contrib.auth.models import User


class  NewUserForm(forms.ModelForm):

    class Meta:
        model=UserProfileInfo
        fields='__all__'

class loginForm(forms.ModelForm):
    password = forms.CharField(widget=forms.Passwordinput())
    class Meta:
        model=Login
        fields="__all__"

class UserForm(forms.ModelForm):
    password=forms.CharField(widget=forms.Passwordinput())
    class Meta:
        model = User
        fields=('username','email','password')

class ContactForm(forms.ModelForm):
    class Meta:
        model = newContactInfo
        exclude=['user_profile_info']

views.py

def contact(request):
    if request.method == "GET":
        contact_form = ContactForm()
        return render(request,"first_app/add_contact.html",context={'add_contact':contact_form})
    if request.method=="POST":
        add_contacts_form = ContactForm(request.POST)  # contact
        profileNameForm = newUserForm(request.POST,request.FILES)
        if add_contacts_form.is_valid() and profileNameForm:
            new_record = add_contacts_form.save(commit=False)
            new_record.user_profile_info=profileNameForm
            add_contacts_form.save()
            return render(request,context={'add_contact':add_contacts_form,'good':"All GOOD"})
        else:
            return render(request,context={'add_contact':add_contacts_form})

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)