Django - 初始化后表单绑定数据

时间:2013-06-08 09:44:23

标签: django django-forms

我有一个user模型,我正在尝试创建一个管理创建/更新表单呈现/发布的视图。

以下是我现在所做的观点

def user_edit(request, user_id=None):
    obj = {}
    status = 200

    if user_id:
        user = get_object_or_404(User, pk=user_id)
    else:
        user = User()

    user_form = UserForm(instance=user, prefix='user')

    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=user, prefix='user')
        if user_form.is_valid():
            user_form.save()
        else:
            status = 406

    obj['user_form'] = user_form
    return render(request, 'user/edit.html', obj, status=status)

这很好用,但正如您所看到的,我的user_form初始化了2次。为了使这更干,在POST时我想更新表单定义而不是重新定义它。类似的东西:

    if request.method == 'POST':
        user_form.data = request.POST
        user_form.prefix = 'user'

但我无法做到这一点。所以有2个问题:

  • 我的观点是否有效?
  • 如何避免表单重新定义?

2 个答案:

答案 0 :(得分:3)

我会用这种方式重构几行:

def user_edit(request, user_id=None):

    status = 200

    if user_id:
        user = get_object_or_404(User, pk=user_id)
    else:
        user = User()

    user_form = UserForm(request.POST or None, instance=user, prefix='user')

    if request.method == 'POST':
        if user_form.is_valid():
            user_form.save()
        else:
            status = 406

    return render(request, 'user/edit.html', {'form': user_form}, status=status)

有时,复制可能是1行代码以保持可读性。

答案 1 :(得分:0)

你应该使用if这样的条件只初始化一次表单:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

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

取自documentation of django。如果您不熟悉Python,在if..else语句中定义变量可能看起来很奇怪,但它在Python中非常常见且有效。