ebong
ebong

Reputation: 65

Django ModelForm with Ajax avoid page refresh

I am new in django and ajax .I have done research but most results i found where hard to understand for me to use in my project .

Bellow is my html code of my form

     <form action='' method="post" enctype='multipart/form-data'>
        {% csrf_token %} {{ form.as_p }}

        <button type="submit">Save changes</button>
    </form>

Here is my view.py which i am passing two modelforms in to same template

def DetailMfg(request,slug):
    instance=get_object_or_404(ManufacturerProfile,slug=slug)
    form =UpdateManufacturerLogo(request.POST or None ,request.FILES,instance=instance)
    form1 = UpdateManufacturerBackgroundprofileForm(request.POST ,request.FILES,instance=instance)
    if request.method == 'POST':
       if form1.is_valid() and form.is_valid():
          instances = form1.save(commit=False)
          instances1 = form.save(commit=False)
          instances1.save()
          instances.save()


       else:
          form=UpdateManufacturerBackgroundprofileForm(instance=instance)
          form =UpdateManufacturerBackgroundprofileForm(instance=instance)

    context={'instance':instance,
         'distributorprofile':distributorprofile,
         'form':form,
         'form1':form1}
    template_name="gbiz1990/User_function_pages/User_company_info_pages/user_mfgprofile_home.html"
    return render(request,template_name,context)

my url

 url(r'^manufacturer_view_profile/(?P<slug>[\w-]+)/$',views.DetailMfg,name="mfgdetail"),

My problem is , which will be best possible way of creating an Ajax function preventing page reload when ever i submit one of the forms in the template, And how will my view look like to accept ajax funtion or data from ajax while preventing page reload .Note i am having more than one django modelform in same template .Thanks in advance .

Here is my model

class ManufacturerProfile(models.Model):
    title = models.CharField(choices=ManufacturerType,max_length=250,blank=False,null=True)
   TypeOfDistributorPrefered =MultiSelectField(choices=Distributortype,null=True,blank=False,max_choices=5)
    verified = models.BooleanField(default=False)
    logo =models.ImageField(upload_to="mfg_logo",null=True,blank=False)
    backgroundimage=models.ImageField(upload_to="mfg_logo",null=True,blank=False)
    slug = models.SlugField(default='page-slug',unique=True)
    promot=models.BooleanField(default=False)
    user =models.ForeignKey(User,unique=True,null=True,on_delete=models.CASCADE)

Upvotes: 1

Views: 1529

Answers (1)

Alvin Lau
Alvin Lau

Reputation: 194

For the first question, please do not use the HTML form to do the POST request. You may use the JQuery on click event listener to listen the submit button click and use $.post() in the event handler to make POST requests to the server.

Please follow the steps below.

Step 1) Add id attribute to the forms to identify all of your forms.

Replace

<form action='' method="post" enctype='multipart/form-data'>

with

<form id="a-good-form-name" action="" method="post"  enctype="multipart/form-data">


Step 2) Change the button type from "submit" to "button" to avoid refresh. Also, add a class name to identify it as an "submit" button.

Replace

<button type="submit">Save changes</button>

with

<button type="button" class="btn-submit">Save changes</button>


Step 3) Create a .js file and import it by putting

<script src="link_of your_file.js"></script>

to the html file. Just put it into the <head></head> part but it must be under the JQuery import tag.


Step 4)Implement event listener and $.post() function inside the event handler.

Add the code below into the .js file you have just created

$(document).ready(function () {

    //Put your JQuery or JavaScript code into here

    $("#a-good-form-name .btn-submit").click(function(){
        $.post("the_url_you_like",{
                data_from_form:$('#a-good-form-name [name="textbox1"]').val(),
                int_data: 123321
            },function(data){
                //What you want to do using the data recieved from the server after POST request made sucessfully.
            }
        });
    });
});

For the second question, you may use

if self.request.is_ajax():

The find out whether the request received is an AJAX request or not.

i.e.

def DetailMfg(request,slug):
    instance=get_object_or_404(ManufacturerProfile,slug=slug)
    form =UpdateManufacturerLogo(request.POST or None ,request.FILES,instance=instance)
    form1 = UpdateManufacturerBackgroundprofileForm(request.POST ,request.FILES,instance=instance)
    if request.method == 'POST' and request.is_ajax():
       if form1.is_valid() and form.is_valid():
          data_you_need=request.POST.get('data_from_form')
          integer_data=request.POST.get('int_data')

          #store data to the database without using form.save() 
          #or do whatever you want using the data

       else:
          form=UpdateManufacturerBackgroundprofileForm(instance=instance)
          form =UpdateManufacturerBackgroundprofileForm(instance=instance)

    context={'instance':instance,
         'distributorprofile':distributorprofile,
         'form':form,
         'form1':form1}
    template_name="gbiz1990/User_function_pages/User_company_info_pages/user_mfgprofile_home.html"
    return render(request,template_name,context)

You have to know that, you do not need a <form> when you make POST request using AJAX. You just need to get all the data you need from the input fields, pack them to be an object, and then make this object as the "data" argument.

Upvotes: 2

Related Questions