Ajax succesfull call show div with form data

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

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

The above views.py and index.html are for saving a new user entry.

My html template is divided into 2 sections, the tab "Main accountant accountant" and the tab "Authorized reporters". the tab "Main accountant accountant" is used to save information about the profile, and the tab "Authorized reporters" is intended to create a new user page. Downloading the main tab “Account Owner” will be active and the user’s tab will be hidden. If the user tab is selected, the tab "Primary account accountant" will be hidden. After the user is saved, the user data is displayed below, in the lower 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 %} 

Actually I want Onclicking <button> id="{{ list.0.id }}" class="openDiv">{{list.0.first_name|title}} {{list.0.last_name}}</button> saved user data should be displayed in the same field in editable mode. I go through the user id in the button. By clicking the button, the data related to the user ID should be displayed 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); } }); }); 

Below are view.py and html to display the saved instance of the form. Now I can show the saved instance of the form, and I load the instance in the authorizedreporter div (please check js and index.html). At this time, if I kit save, it creates a new record, it calls view.py associated with the index.I method I want to update and not save the record.

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 have explained my current problem that I am facing, please help me with this. thanks

+4
source share
3 answers

Let me analyze your JS code a bit, as I see a few errors / errors:

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

Well, as I understand it, after clicking the link, you use AJAX to submit the request to the Django view in order to return the correct instance form. Therefore, you must:

First, simplify the JS code:

 $('.openDiv').click(function (e) { e.preventDefault(); var this_id = $(this).closest('td').attr('id'); // get the user ID, since that 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(); } }); }); 

Then divide your old view into several views in order 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') 

Here you can see two functions: 1 to get the correct form from AJAX, the other to save data through the usual submit form. Of course you should do 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'), ) 

You may also notice that you must create a new setting/register_form.html template that includes only your HTML login form (note: you need a hidden id field that was returned as fetch_reporter_form above to define 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> 

So the thread:

  • Go to index . There are several forms for saving a new reporter, etc. As usual.
  • Click the .openDiv button. It will send an AJAX request above fetch_reporter_form to get the correct form. (Right now your code is working fine)
  • Click the "Save" button in this form, it will present the updated data (via POST) in update_report and update the reporter.

I'm just trying to give you a basic idea. The rest is pretty simple, so I think you can go on easily. Hope this helps!

+3
source

Let me resume what you are doing:

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

Here you configure the asynchronous Ajax request to send data to the server. When the request reaches the server, if it does not fail, the success: callback is called and javascript does nothing ( return true; ).

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

Here you show the HTML node before the asynchronous Ajax request completes (is being executed or is failing). To show an item after executing an Ajax request, put this code inside the success: or error: callback.

Finally, if you count your ( , ) , { and } , you will see that $('#authorisedreporter').show(); is out of callback. Therefore, if he leaves the finished document, he will not have any effect.

So the correct Javascript code should be (I think):

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

EDIT:

About your view.py, you save the UserProfile but don't return anything to the client browser. Nothing.

 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 ? 
+1
source

Check for error messages returned from the server:

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

});

Edit

You do not pass the user ID when submitting the form. Try to do something like:

 <form ...> <!-- //.. --> {{ form.id.as_hidden }} </form> 
0
source

Source: https://habr.com/ru/post/1493685/


All Articles