微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在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 举报,一经查实,本站将立刻删除。