4

视图.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,})

索引.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 用于保存新的用户条目。

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

{% 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 %}

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

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 是为显示保存的表单实例而编写的。现在我可以显示保存的表单实例,并且我正在将实例加载到授权报告器 div 中(请检查 js 和 index.html)。这次如果我有套件保存,它正在创建新记录,它正在调用与索引方法相关的views.py。我想更新而不是保存记录。

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>

视图.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
                    })

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

4

3 回答 3

3

让我稍微分析一下您的 JS 代码,因为我可以在那里看到几个错误/错误:

$('.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 视图发送请求以取回正确的实例化表单。所以你应该:

首先,简化你的 JS 代码:

$('.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();
        }
   });
});

接下来,将您的旧视图拆分为几个视图,以专注于它需要做的事情(注意:您可以保留您index现在的视图):

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')

您可以看到这里有 2 个功能:1 用于从 AJAX 获取正确的表单,另一个用于通过普通表单提交保存数​​据。当然,您应该urls.py相应地进行,例如:

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仅包含您的注册表单 HTML 的新模板(注意:您需要一个由上面的视图id返回的隐藏字段fetch_reporter_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看看。有几种表格可以正常保存新记者等。
  2. 你点击.openDiv按钮。它将发送上面的 AJAX 请求fetch_reporter_form以获取正确的表单。(此时您的代码运行良好)
  3. 您单击该表单上的保存按钮,它将提交更新的数据(通过 POST)以update_report查看和更新​​报告者。

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

于 2013-07-31T21:21:45.253 回答
1

让我继续你正在做的事情:

$.ajax({ 
    data:{
        /* ... */
    },
    type:'POST',
    url: '/report/save_reporter/',
    success: function() {
        return true;
    }
});

在这里,您设置了一个 Ajax 异步查询以将数据发布到服务器。当查询到达服务器时,如果它没有崩溃,则success:调用回调并且 javascript 什么也不做 ( return true;)。

$('#authorisedreporter').show();

在这里,您将在异步 Ajax 查询结束(成功或失败)之前显示一个 HTML 节点。要在 Ajax 查询完成后显示元素,请将此代码放在success:orerror:回调中。

最后,如果你算上你的, ()你会看到在点击回调之外。因此,如果超出了文档就绪回调,将没有任何效果。{}$('#authorisedreporter').show();

所以正确的Javascript代码应该是(我认为):

$('.openDiv').click(function (e) {    
    e.preventDefault();          
    var id = $(this).attr('id');  
    var firstname = $("#"+id).find('#id_first_name').val();    
    var phonemobile = $("#"+id).find('id_phone_mobile').val();    
    $.ajax({ 
        data:{
            csrfmiddlewaretoken: csrf_token,
            edit_reporter:true,
            id:id,
            first_name:firstname,               
            phone_mobile:phonemobile,
        },
        type:'POST',
        url: '/report/save_reporter/',
        success: function() {
            $('#authorisedreporter').show();
        }
   });
});

编辑:

关于您的 view.py,您保存了一个 UserProfile 但不向客户端浏览器返回任何内容。没有什么。

def save_reporter(request):
    user=User.objects.get(user=user) # you should use django.shortcuts.get_object_or_404
    userprofile = Userprofile.objects.get(user=user) # same comment
    if request.method == 'POST':
        registerform = UserRegisterForm(request.POST,instance=user)
        createprofileform = UserCreateProfileForm(request.POST,instance=userprofile)
        # you create 2 forms above, but don't use them. Is it normal ?!
        # you should do loops "if registerform .valid(): ... else: ..." and use it. Same for the 2nd form
        if 'edit_reporter' in request.POST:
            first_name=request.POST.get('first_name') # can be None
            phone_mobile = request.POST.get('phone_mobile') # can be None      
            user = User.objects.get(pk=user)
            user.first_name = first_name            
            user.save() # put it inside a try/except statment
            userprofile = UserProfile.objects.get(pk=user) # use get_or_404
            userprofile.phone_mobile = phone_mobile 
            userprofile.save() # put it inside a try/except statment
    return HttpResponse() # this returns an empty html page, do you want to return the form here ?
于 2013-07-26T14:37:43.937 回答
0

检查服务器是否返回任何错误消息:

$.ajax({ 
    // ...
    error: function(err) {
        console.log(err);
    }

});

编辑

提交表单时不传递用户 ID。尝试做类似的事情:

<form ...>
   <!-- //.. -->
   {{ form.id.as_hidden }}
</form>
于 2013-08-07T05:32:17.453 回答