如何通过父ID向子表单添加值?

时间:2019-09-03 07:43:06

标签: python django

这是我的模特

class User(models.Model):
    name = models.CharField(max_length=50)
    surname = models.CharField(max_length=50)


class Phone(models.Model):
    user = models.ForeignKey(Osoba, editable=False, related_name='phone', on_delete=models.CASCADE)
    phone = models.CharField(max_length=50)

并且我想将电话添加到ID选择的当前用户并在网站上显示

我已经尝试过

def create_phone(request, id):

    user = User.objects.get(id=id)
    form = PhoneForm(request.POST or None, instance=user)

    if form.is_valid():

        form.save()
        return redirect('list_users')

    return render(request, 'index-phone.html', {'form': form})

但是它不起作用,当我单击按钮时,它不会创建新电话

我的网址

urlpatterns = [
    path('', list_users, name='list_users'),
    path('new', create_user, name='create_user'),
    path('/<int:id>/update', update_user, name='update_user'),
    path('/<int:id>/delete', delete_user, name='delete_user'),
    path('/<int:id>/', create_phone, name='create_phone')

]

1 个答案:

答案 0 :(得分:0)

我不确定您的PhoneForm类的内容,但是我想那是用于创建和编辑Phone对象的表单。实例化新的PhoneForm时,实例参数应该是现有的Phone实例,或者是None。

您应该以其他方式设置Phone实例的用户,方法是将其设置为PhoneForm上的字段,或者手动设置用户。

这是正确的:

def create_phone(request, id):

    user = User.objects.get(id=id)
    form = PhoneForm(request.POST or None)

    if form.is_valid():

    # Setting commit to False does not save the object to the database yet.
    # We do this because we still want to edit the object.
    phone = form.save(commit=False)
    phone.user = user
    phone.save()
    return redirect('list_users')

return render(request, 'index-phone.html', {'form': form})