Ajax使用表单数据调用show div [英] Ajax succesfull call show div with form data

查看:151
本文介绍了Ajax使用表单数据调用show div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

views.py

def index(request):
    """"""""""""""
    registerform = UserRegisterForm(request.POST)
    createprofileform = UserCreateProfileForm(request.POST)                            
    if registerform.is_valid() and createprofileform.is_valid():               
        result = registerform.save(commit=False)
        result.set_password(request.POST['password'])        #set member password
        result.username = username               
        result.save()
        member.user_id = user.id
        member.member_id = result.id
        member.save()                                        #new member registration
        member_profile = UserProfile.objects.get(user=result.id)
        createprofileform = UserCreateProfileForm(request.POST, instance=member_profile)
        createprofileform.save()                             #create member profile                
        createprofileform = UserCreateProfileForm()
        member_save_msg = 'New member has been added.' 
        """"""""""""
    return render(request,'index.html',{ 'registerform': registerform,'createprofile': createprofileform,})

index.html

index.html

{% block main-content %}
<table width="98%" border="0" style="margin-left:0.7%;" cellpadding="0" cellspacing="0" id="rounded_table">
    <tr >
         <td width="50%">Main Account Holder</td><td width="50%">Authorised Reporters</td>
    </tr>
     <tr id="main_account">
          <td width="50%">All data related to main account holder comes here</td>
     </tr>
     <tr id="authorised_reporter">
          <td  width="100%" colspan="2">
           <div id="authorisedreporter" {% if not registerform.errors %}style="display:none"{% endif %}>
                <form method="post" action="." id="reporter-form">{% csrf_token %}
                <table  width="100%">
                  <tr>
                     <td style="width:100px;">First name:</td><td>{{registerform.first_name}}</td>
                  </tr>
                  <tr>
                     <td>Last name:</td><td>{{registerform.last_name}} </td>
                  </tr>
                         """"""other form fields""""""""
                  <tr>
                     <td colspan=2""><p align="right"><button type="submit" title="Save" >Save <img src="{{ STATIC_URL }}images/button-icon-ir-fwd.png" width="12" height="17" alt="" /></button></p>
                     </td>
                  </tr>
                  </table></form>
</table>
{%endblock%}

上面的views.py和index.html用于保存新用户条目。

The above views.py and index.html is for saving the new user entry.

我的html模板分为2个部分,主账户持有人选项卡和授权记者选项卡。主账户持有人选项卡用于保存个人资料信息和授权记者选项卡用于创建新用户。页面加载主帐户持有者选项卡将被激活,用户选项卡将被隐藏。如果选择了用户选项卡,主账户持有者选项卡将被隐藏。一旦用户被保存,用户的详细信息将在下面显示,格式如下。

My html template is divided into 2 section,Main Account Holder tab and Authorised Reporters tab.Main Account Holder tab is for saving profile info and Authorised Reporters tab is for creating new user.on page load Main Account Holder tab will be active and user tab will be hidden.If user tab is selected,Main Account Holder tab will be hidden.Once the user is saved,the user details are displayed below, in below format.

{% for list in member_list %}
       <tr class="ir-shade"> 
        <td style="width:120px;"><span><input type="submit" name="delete" value="{{list.0.id}}" class="delete_reporter" /></span><button> id="{{ list.0.id }}" class="openDiv">{{list.0.first_name|title}} {{list.0.last_name}}</button></td>
       <td style="width:410px;"> {{list.0.email}} {{list.1.phone_daytime}} {{list.1.phone_mobile}}</td>
       </tr>
    {% endfor %}

我真正想要的是放下<按钮> id ={{list.0.id}}class =openDiv> {{list.0.first_name | title}} {{list.0.last_name}}< / button> 保存的用户数据应该在可编辑模式下显示在相同的字段中。我在按钮中传递用户ID。点击按钮,与用户ID相关的数据应显示为可编辑模式。

What i actually want is Onclicking the <button> id="{{ list.0.id }}" class="openDiv">{{list.0.first_name|title}} {{list.0.last_name}}</button> saved user data should shown in same field in editable mode.i am passing the user id in button.On click the button,the data related to user id should shown in editable mode.

js:

   $('.openDiv').click(function () {              
    var id = $(this).attr('id');  
    var csrf_token = $("#csrf_token").val();
    $.ajax({ 
       data:{
            csrfmiddlewaretoken: ('{{csrf_token}}'),                          
            id:id,                
            },
    type:'POST',
    url: '/setting/save-reporter/',
    success: function(data) {
        $('#authorisedreporter').html(data);
    }
  });
 });

下面的views.py和html是为了显示保存的表单实例而编写的。现在我可以显示保存的表单实例,我正在将实例加载到authorisedreporter div(请检查js和index.html)。在这个时候如果我的工具保存,它创建新的记录,它正在调用与.pyindex相关的views.py。想要更新而不保存记录。

The below views.py and html are written for showing the saved form instance.Now i can show the saved form instance and i am loading the instance into authorisedreporter div(please check in js and index.html).In this time if i kit save,it is creating new record,it is calling the views.py related to index method.I want to update and not save the record.

save_reporter.html

save_reporter.html

<form method="post" action="." id="{{ id }}">
    {% csrf_token %}
    <table  width="100%">
        <tr>
            <td style="width:100px;">First name:</td><td>{{form.first_name}}</td>
        </tr>
        <tr>
            <td>Last name:</td><td>{{form.last_name}}</td>
        </tr>
        <tr>
            <td>Daytime phone:</td><td>{{profile.phone_daytime}}</td>
        </tr>
        <tr>
            <td>Mobile phone:</td><td>{{profile.phone_mobile}}</td>
        </tr>
        <tr>
            <td>Email:</td><td>{{form.email}}</td>
        </tr>
        <tr>
            <td>Password</td><td>{{form.password}}</td>
        </tr>
        <tr>
           <td colspan=2"<p align="right">{% include "buttons/save.html" %}</p></td>
        </tr></table></form>

views.py

def save_reporter(request):
    user = request.user
    id = request.POST.get('id')
    user = User.objects.get(pk =id)
    userprofile = UserProfile.objects.get(user=user.id)
    form = ReporterRegisterForm(instance=user)
    profileform = ProfilecontactForm(instance=userprofile)               
    return render(request, 'setting/save_reporter.html',
                   {'form': form,
                    'id':id,
                     'profile':profileform
                    })

我已经解释了我目前面临的问题,请有帮助我这样做。谢谢

I had explained my current issue i am facing,please have help me in doing this.Thanks

推荐答案

让我分析一下你的JS代码,si nce我可以看到几个错误/错误:

Let me analyze your JS code a bit, since I can see several errors/mistakes there:

$('.openDiv').click(function (e) {       
    e.preventDefault();

    // where is following data taken from? At the point you click the .openDiv link, the form doesn't have any data yet so all of them will be empty string ''
    var csrf_token = $("#csrf_token").val();
    var id =  $(this).closest('td').attr('id');
    var firstname = $("#"+id).find('#id_first_name').val();
    var lastname = $("#"+id).find('#id_last_name').val();
    var phonedaytime = $("#"+id).find('#id_phone_daytime').val(); 
    var phonemobile = $("#"+id).find('#id_phone_mobile').val();
    var email = $("#"+id).find('#id_email').val();

    // do you use AJAX to get the form or use it to save the form?
    $.ajax({ 
        data: $(this).serialize(), // this is wrong, $(this) is the link object, not a form
        type:'POST',
        url: '/setting/save-reporter/',
        success: function(data) {
            $('#authorisedreporter').html(data);
            $('#authorisedreporter').show();
        }
   });
});

根据我的理解,点击链接后,您正在使用AJAX向Django发送请求查看以获取正确的实例化表单。所以你应该:

Ok as far as I understand, after clicking the link, you are using AJAX to send request to Django view to fetch back the correct instantiated form. So you should:

首先,简化你的JS代码:

First, simplify your JS code:

$('.openDiv').click(function (e) {       
    e.preventDefault();
    var this_id =  $(this).closest('td').attr('id'); // get the user ID, since that's all you need
    console.log(this_id); // making sure that you get the right ID
    $.ajax({ 
        data: { id: this_id },
        type: 'POST',
        url: '/setting/fetch-reporter-form/',
        success: function(data) {
            $('#authorisedreporter').html(data);
            $('#authorisedreporter').show();
        }
   });
});

接下来,将您的旧视图拆分为几个视图,专注于需要做什么(请注意:您可以离开您的索引视图,现在):

Next, split your old view to several views to focus on what it needs to do (note: you can leave your index view as it is now):

def fetch_reporter_form(request):
    ''' Change your save_reporter view name to this view '''
    registerform = UserRegisterForm()

    if request.method == 'POST':
        id = request.POST.get('id', None)
        if id:
            user = get_object_or_404(pk=user.id)
            userprofile = UserProfile.objects.get(user=user)
            registerform = UserRegisterForm(request.POST, instance=user)
            return render(request, 'setting/register_form.html', {
                'user_id': id
                'registerform':registerform
            })
        else:
            return HttpResponse('Request does not contain any ID')
    else:
        return HttpResponse('Request is not POST')

def update_reporter(request):
    ''' This function is for update the reporter '''
    registerform = UserRegisterForm()

    if request.method == 'POST':
    id = request.POST.get('id', None)
        if id:
            user = get_object_or_404(pk=user.id)
            userprofile = UserProfile.objects.get(user=user)
            registerform = UserRegisterForm(request.POST, instance=user)
            if registerform.is_valid():
                result = registerform.save(commit=False)

                # saving code here ...
                return HttpResponse('Success')
        else:
            return HttpResponse('Request does not contain any ID')
    else:
        return HttpResponse('Request is not POST')

你可以看到这里有两个功能:1,从AJAX中获取正确的表单,其他用于通过正常的表单提交保存数​​据。当然,您应该相应地使 urls.py ,如下所示:

You can see here there are 2 functions: 1 for fetching the right form from AJAX, the other for saving the data via normal form submit. Of course you should make the urls.py accordingly, something like:

urlpatterns = patterns('',
    # ... your code ...
    url(r'^setting/fetch-reporter-form/$', 'yourapp.views.fetch_reporter_form'),
    url(r'^setting/update-reporter/$', 'yourapp.views.update_reporter'),
)

您可能还会注意到,您应该只创建一个新的模板 setting / register_form.html ,只包含您的注册表单(注意:您需要由 fetch_reporter_form 视图返回的隐藏的 id 字段以识别表单):

You might also notice that you should make a new template setting/register_form.html that include your registration form HTML only (note: you need a hidden id field that was returned by fetch_reporter_form view above to identify the form):

<form method="post" action="/setting/update-reporter" id="reporter-form">
    {% csrf_token %}
    <input type="hidden" name="id" value="{{ user_id }}" />
    <!-- your code here -->
</form>

所以流程是:


  1. 你去 index view。有几种形式可以正常保存新的记者等。

  2. 您点击 .openDiv 按钮。它会将AJAX请求发送到 fetch_reporter_form 以获取正确的表单。 (您的代码现在正常工作)

  3. 您单击该表单上的保存按钮,它将通过POST将更新后的数据提交到 update_report 查看和更新​​记者。

  1. You go to index view. There is several forms to save new reporter, etc. as normal.
  2. You click on the .openDiv button. It will send the AJAX request above to fetch_reporter_form to get the correct form. (Your code is working fine at this point)
  3. You click Save button on that form, it will submit the updated data (via POST) to update_report view and update the reporter.

我只是想给你一个基本的想法。其余的很简单,所以我猜你可以继续轻松希望有帮助!

I'm just trying to give you the basic idea. The rest is quite straightforward so I guess you can continue easily. Hope it helps!

这篇关于Ajax使用表单数据调用show div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆