保存时在db中复制数据(Django表单)

时间:2015-10-31 19:29:54

标签: django django-forms django-templates django-admin django-views

我创建了一个表单,当输入页面从json文件加载初始数据然后我可以编辑并以相同的形式保存数据。所有工作都很完美,但每次按下提交按钮数据库都接受两行相同的数据。任何帮助赞赏。

views.py

def form_save_and_edit(request, id=None, template_name='create.html'):

""" referring data from "model_from_json()",
making data visible within another function """

func = model_from_json()

""" savind and editing form data in the same form """

form = UserDataForm(request.POST)
if request.POST:

    updated_field = form.save()
    last_name = request.session['last_name'] = updated_field.last_name
    first_name = request.session['first_name'] = updated_field.first_name
    email = request.session['email'] = updated_field.email
    skype = request.session['skype'] = updated_field.skype

    form = UserDataForm({
    'last_name': last_name,
    'first_name': first_name,
    'skype':skype,
    'email':email
    })

    redirect_url = reverse('create')
    message = messages.success(request, "You successfully updated your profile!")
    if form.is_valid():
        form.save()
else:

    form = UserDataForm({
        'last_name': func['last_name'],
        'first_name':func['first_name'],
        'email':func['email'],
        'skype':func['skype'],

        })

    message = messages.success(request, "You just loaded your profile initial data")
return render_to_response('create.html', {'form': form,}, context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:1)

您似乎在form.save()语句中调用了两次。一旦在方法的开头,这里:

    updated_field = form.save()

最后的另一个:

    if form.is_valid():
    form.save()