简体   繁体   中英

Django form Inserts record instead of update

when i use the id parameter from the url to edit a record, and the "elif 'id' in request.GET:" is being used, it doesn't update the record but it creates a new row

@login_required
def login_save_page(request):
    if request.method == 'POST':
        form = LoginSaveForm(request.POST)
        if form.is_valid():
            # Create or get login.
            login1 = _login_save(request, form)
            return HttpResponseRedirect(
                                        '/user/%s/' % request.user.username
                                       )
    elif 'id' in request.GET:
     id2 = request.GET['id']
     name=''
     url=''
     Login_username =''
     notes= ''
     password=''
     try:
        login1 = login.objects.get(
                                   id = id2,
                                   username=request.user
                                  )
        name = login1.name
        url = login1.loginUrl
        Login_username = login1.login_username
        notes = login1.notes
        password = login1.password
     except (login.DoesNotExist):
      pass
     form = LoginSaveForm({
        'id': id2,
        'name': name,
        'url': url,
        'Login_username': Login_username,
        'notes': notes,
        'password': password
     })
    else:
        form = LoginSaveForm()
    variables = RequestContext(request, {
                                   'form': form
                                             })
    return render_to_response('login_save_page.html', variables)

I'm assuming your form is submitting via POST thus the elif "get" will never fire when you need it to (when the user submits the form).

You'll need to put that logic inside of the if request.method == 'POST' block.

Think about when that "elif" block will trigger. Only when the request method is not POST , which means only on page load.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM