Django Forms with get_or_create

前端 未结 5 964
清酒与你
清酒与你 2021-01-31 09:46

I am using Django ModelForms to create a form. I have my form set up and it is working ok.

form = MyForm(data=request.POST)

if form.is_valid():
    form.sav         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-31 10:13

    What do you mean by "if an identical record exists"? If this is a simple ID check, then your view code would look something like this:

    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        if get_id:
            obj = MyModel.objects.get(id=get_id)
            form = MyForm(instance=obj)
        else:
            form = MyForm()
    

    The concept here is the check occurs on the GET request, such that on the POST to save, Django will already have determined if this is a new or existing record.

    If your check for an identical record is more complex, it might require shifting the logic around a bit.

提交回复
热议问题