无法分配:must be a instance Django foreign Key error with html form

eit6fx6z  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(223)

我正在使用Foregin Key。在下拉菜单中,我传递Foregin键值。在表中存储数据时,我得到示例错误
我尝试从关系表中获取数据并传递该ID。
models.py

class Contacts(models.Model): #client's point of contact
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    phone = models.CharField(max_length=100)
    mobile = models.CharField(max_length=100)
    role = models.CharField(max_length=100)
    title = models.CharField(max_length=100)

views.py

def add_contacts(request):
    if request.method == "POST":
        user_dt = request.POST['user']   
        client_dt = request.POST['client']
        client = request.POST['client']
        name = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        mobile = request.POST['mobile']
        role = request.POST['role']
        title = request.POST['title']
        print(user,client,name,email,phone,mobile,role,title)
        data = Contacts.objects.create(user=user,client=client,name=name,email=email,phone=phone,mobile=mobile,role=role,title=title)
        print(data)
        return redirect('contacts')
6kkfgxo0

6kkfgxo01#

也许你可以这样做:

def add_contacts(request):
    if request.method == "POST":
        user_id = request.POST['user']   
        client_id = request.POST['client']
        name = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        mobile = request.POST['mobile']
        role = request.POST['role']
        title = request.POST['title']

        data = Contacts.objects.create(
            user_id=user_id, # call user_id instead "user" only
            client_id=client_id, # call client_id instead "client" only
            name=name,
            email=email,
            phone=phone,
            mobile=mobile,
            role=role,
            title=title,
        )

一旦userclientContacts模型上的外键,你就可以像上面一样直接解析id了。
另一个建议是使用get dict函数,以避免一些KeyErrors。我的意思是:

request.POST.get('name', <default_value>) 
# instead
request.POST['name']
t40tm48m

t40tm48m2#

这是因为Model需要userclient的示例对象,因为这两个字段都是外键,所以你必须检索它们来创建你的Contacts对象(例如:Client.objects.get(pk=client))。
从外观上看(分别检索每个字段),您没有使用Django forms。有了这么多的字段和嵌套对象,我会考虑创建一个,让框架来完成它的工作,下面是一个使用ModelForm的例子:
forms.py

class ContactForm(ModelForm):
    class Meta:
        model = Contacts
        fields = [
            "user", "client", "name", 
            "email", "phone", "mobile", 
            "role", "title"
        ]

views.py

def add_contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            # You probably want to redirect somewhere else
            return redirect("add-contact")
    else:
        form = ContactForm()

    return render(request, "add_contact.html", {"form": form})

add_contact.html

...
<form method="post" action="{% url 'add-contact' %}">
    {%csrf_token%}
    {{form.as_p}}
    <button type="submit" >Create Contact</button>
</form>
...

urls.py

urlpatterns = [
    path('contact/add/', add_contact, name='add-contact')
]

相关问题