使用AJAX创建一个Object,然后在下拉框中显示

时间:2014-06-02 11:42:46

标签: ajax django view

嗨,我遇到了一个问题,我试图这样做,所以当点击一个按钮时,可以制作一个对象。我无法让它工作,因为它不会验证,但是如果我改变输入类型提交它工作正常。

但问题是当我使用它作为提交页面重定向时,这违背了使用AJAX的目的。

我似乎无法为我想做的事找到一个好的教程,真的很感激任何帮助或链接!

模型

class MemberRole(models.Model,get_fields):
    name = models.CharField(max_length = 20)

表格

class MemberRoleForm(forms.ModelForm):
    class Meta:
        model = MemberRole

视图 此视图构建了memberrole模型的表单

def add_member(request):
    model_url = 'member-add'
    rform = MemberRoleForm(instance=MemberRole())
    return render_to_response('create_model.html', {'role_form': rform,'model_url': model_url,},context_instance=RequestContext(request))

这个ajax叫做视图

@require_POST
def ajax(request):
    data = request.POST.get("rolename","")
    if request.method == 'POST':
        rform = MemberRoleForm(request.POST, instance=MemberRole())
        if rform.is_valid():
            new_role = rform.save()
            new_role.name = data
            return HttpResponse("SuccessFully Saved")
        else:
            return HttpResponse("Error in saving")

模板

    <div id="addRoleOnMemberForm">
        <form id = "addrole" onsubmit= "return false;" method="POST">
        {% csrf_token %}
        {% for field in role_form %}
                {{ field.errors }}
                {{ field.label_tag }} {{ field }} //#id_name is in here
        {% endfor %}
        <input id="addrolebutton" type="button" onclick = "createit()" value="Add New Role"/>
    </div>
    {% for x in role_list %}

    <div>
        <p> This shows a role was made </p>
    </div>
    {% endfor %}

脚本

<script>
    function createit(){
    $.ajax({
    type: "POST",
    url:"ajax",
dataType:"json",
async: true,
data: {
    csrfmiddlewaretoken: '{{ csrf_token }}',
rolename: $('#id_name').val()
},

});
}
</script>

1 个答案:

答案 0 :(得分:1)

我终于设法让它发挥作用。 :)

我有一个add_member视图,如果在member.role下拉字段中不可用,则允许创建一个memberrole对象。创建时的memberrole对象将在没有页面重新加载的情况下添加到下拉字段中,因此可以立即选择它。

我不完全确定这是否是正确的编码方式,我已经包含了所有来源,希望它可以帮助像我这样的人。评论将不胜感激!

<强>模型

class MemberRole(models.Model,get_fields):
    name = models.CharField(max_length = 20)

class Member(models.Model,get_fields):
    first_name = models.CharField(max_length = 20)
    last_name = models.CharField(max_length = 20)
    role = models.ForeignKey(MemberRole, null = True, blank = True)

<强>表单

class MemberForm(forms.ModelForm):
    class Meta:
         model = Member

<强>脚本

<script>
        function createit(){
                $.ajax({
                    type: "POST",
                    url:"addrole",
                    dataType:"json",
                    async: true,
                    data: {
                        csrfmiddlewaretoken: '{{ csrf_token }}',
                        rolename: $('#role_name').val()
                    },
                    success: function (json,rolename){
                        $('#output').html(json.message); // Prints a message to say that the MemberRole object was created
                        $('#roleExistsMemberForm').load(document.URL + ' #roleExistsMemberForm'); //Refreshes the dropdown box so that the newly created MemberRole can be selected
                    }
                });
            }
    </script>

<强>视图

def add_role(request):
    model_url = 'role-add'
    new_role = request.POST.get("rolename","")
    role_list = MemberRole.objects.all()
    response_data= {}

    if new_role:
        x = MemberRole()
        x.name = new_role
        x.save()
        response_data['message'] = new_role + " was created"
    else:
        response_data['message'] = 'Nothing created'

    return HttpResponse(json.dumps(response_data),content_type="application/json")

def add_member(request):
    model_url = 'member-add'

    if request.method == "POST":
        mform = MemberForm(request.POST, instance=Member())
        if mform.is_valid():
        new_member = mform.save(commit=False)
        new_member.save()
        return HttpResponseRedirect('members')
    else:
        mform = MemberForm(instance=Member())
    return render_to_response('create_model.html', {'member_form': mform, 'model_url': model_url,},context_instance=RequestContext(request))

<强> create_model.html

{% for field in member_form %}
{% if field.label == 'Role' %}
<div id="roleExistsMemberForm">
            {{ field.errors }}
            {{ field.label_tag }} {{ field }}
        </div>
        {% else %}
        <div class="fieldWrapper">
            {{ field.errors }}
            {{ field.label_tag }} {{ field }}
        </div>
    {% endif %}
    {% endfor %}
        <div id="addRoleOnMemberForm">
        <form onsubmit="return false;">
        {% csrf_token %}
        <input id= "role_name" type="text"/>
        <input id="addrolebut" type="button" onclick = "createit()" value="Add New Role"/>
    </div>
    <div id="output">
    <p>Nothing here</p>
</div>