[Answer]-Using AJAX to create an Object which then appears in dropdown box

1๐Ÿ‘

โœ…

Iโ€™ve finally managed to get it to work. ๐Ÿ™‚

I have an add_member view which allows the creation of a memberrole object if it is not available in the member.role dropdown field. The memberrole object on creation will be added without a page reload to the dropdown field so it can be selected immediatly.

Iโ€™m not entirely sure if this would be the correct way of coding it, Iโ€™ve included all the source and hopefully it helps someone like me. Comments would be appreciated!

Models

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)

Forms

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

Script

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

Views

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>

๐Ÿ‘คtama

Leave a comment