创建表单并使用Django中的相同视图进行更新

时间:2019-04-17 14:00:06

标签: django django-forms

我正在尝试使用相同的视图来创建表单和更新任何对象。

我的代码如下,我以多种方式尝试了无济于事,因为我将shof从表单中排除,并在form.is_valid()之后添加它,这引起了很多混乱。如果我更新它会创建新对象。我有两个URL,一个不带ql(创建新的),另一个不带ql(更新现有的),我有一个类vdview,它提供v.shof,它需要以形式应用于f.shop。请帮助解决此问题,

@csrf_protect
@login_required
def addmenu(request, qs, ql=None):
    v = vdview(request, qs)
    ctgobj =  get_object_or_404(v.shopcategs, pk=ql) if ql else None #  ctgobj = ShopCtg(shop=v.shof)
    if ql:
        form = ShopCtgForm(instance=ctgobj) # Tried ShopCtgForm(instance=ctgobj, data=request.POST)
    else:
        form = ShopCtgForm(data= request.POST)
    if request.method == 'POST':
        if form.is_valid():
            f=form.save(commit=False)
            f.shop = v.shof
            f.save()
            #form.save_m2m()
            return redirect('vendor-shop', qs) #thing='%s added' %f.name)
        else:
            pass
    #else:
    #    form = ShopCtgForm()
    return render(request,'vendorshop.html', {'shop':v.shof, 'shopcategs':v.shopcategs, 'form': form,
    'heading':'Create New Category', 'createcateg': 'createcateg', 'pkaddmenupk':'y'    }    )

1 个答案:

答案 0 :(得分:0)

使用try块来处理这两种情况。下面的简化示例将查找给定的模型实例pk,如果找不到它,则假定您要创建它。如果模型实例不存在,try将防止django引发错误。相反,它将仅返回空的模型形式。

首先执行此操作以在模板(第一个try块中呈现正确的表单,然后在try之后的第二个request.method == 'POST':块中呈现正确的表单,以提交新数据或更新现有数据

Views.py

from .models import Books
from .forms import BookForm

def create_and_update_book_view(request, pk):

    books = Books.objects.get(id=pk)

    try: # get pre-populated form with model instance data (for update)
        form = BookForm(instance=books.id) 
    except: # If it doesn't exist, show an empty form (for create)
        form = BookForm(request.POST or None)

    if request.method == 'POST':
        try: # Do the same as above
            form = BookForm(instance=books.id)
        except: # Same as above
            form = BookForm(request.POST or None)
        if form.is_valid():
            form.save()

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