Why is the form not being displayed? - ajax

I am using django and ajax to submit a form, but when the form is invalid then it's not been displayed.
# views.py
class ProductCreateView(LoginRequiredMixin, CreateView):
model = Product
template_name = "products/my_products.html"
form_class = AddNewProductForm
def form_valid(self, form):
obj = form.save(commit=False)
obj.user = self.request.user
obj.save()
return JsonResponse({"msg": "Your product was created successfully."})
def form_invalid(self, form):
return render(self.request, "products/add_new_product.html", {"form": form}, status=400)
saveNewProductButton.on("click", function () {
var addNewProductForm = $(".add-new-product-form");
$.ajax({
type: 'POST',
url: '/product/new/',
data: addNewProductForm.serialize(),
success: function(res){
alert(res['msg']);
location.reload();
},
error: function (res) {
var newProductPlaceHolder = $("#new-product-form-placeholder");
newProductPlaceHolder.html(res);
}});
});
The res is shown in the console using Chrome, but not on the page.

Related

Django generics view not showing HTML template (using AJAX to access the Django view)

I am trying to access Django view via AJAX and show the data returned by view in HTML page. I am using using Django Rest generics view.
Django view returns response successfully. Then, the page reloads.
But html page has not been shown.
HTML code:
Apply filters
Javascript code:
$("apply-link").click(function(){
filterData(j_data);
});
function filterData(j_data) {
let url = "filter";
const csrftoken = getCookie('csrftoken');
$.ajax({
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
url: url,
data: j_data,
success: function (result) {
console.log(result);
},
error: function (response) {
console.log("error");
}
});
}
views.py
class FilterView(generics.CreateAPIView):
template_name = 'pwa_app/filters.html'
serializer_class = ProductSerializer
def post(self, request):
data = request.data
page = self.paginate_queryset(all_products)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(all_products, many=True)
return Response(serializer.data)
urls.py
path('filter', FilterView.as_view(), name="filter")

How to put a alert error message in django form?

I have actually followed this tutorial to perform ajax request on error in form field.
Then I performed the following:
My models:
class Company(models.Model):
user = models.ForeignKey(User,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True)
name = models.CharField(max_length=50,blank=False)
books_begining_from = models.DateField(default=datetime.date(2018,4,1), blank=False)
gst_enabled = models.BooleanField(default=False)
composite_enable = models.BooleanField(default=False)
My views:
def validate_gst_billing(request):
data = {
'is_enable' : Company.objects.filter(gst_enabled = False,composite_enable = True)
}
if data['is_enable']:
data['error_message'] = 'To enable composite billing GST should be enabled'
return JsonResponse(data)
In my html:
<script>
$("#id_composite_enable").change(function () {
var form = $(this).closest("form");
$.ajax({
url: form.attr("data-validate-gst-billing-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
if (data.is_enable) {
alert(data.error_message);
}
}
});
});
</script>
I want to throw an error message to the users as an alert if they try to submit a form with the gst_enable field set to False and the composite_enable field set to True.
Any idea what is wrong in my code?
Thank you
I think you should use error method in ajax like this :
$.ajax({
url: '/api/list',
success: function(data , textStatus ,jqXHR){
console.log(data)
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus)
console.log(errorThrown)
}
});
you can right click in your page select inspect element and in the console tab see your console log
For what I see, you are not setting any boolean on 'is_enable'. Add .exists() method to the queryset to get a boolean.
def validate_gst_billing(request):
data = {
'is_enable' : Company.objects.filter(gst_enabled=False, composite_enable=True).exists()
}
if data['is_enable']:
data['error_message'] = 'To enable composite billing GST should be enabled'
return JsonResponse(data)

AJAX gets access to Django HttpResponse variables

I am writing a small test app for a bigger project. I would like to use asynchronously FileReader() to read a txt file from client side and pass the textbody to the Django server by using AJAX. When the server succeeds to get the "posted" text, it will return the length of the text. It worked well on the server and I got what I expected. But now I would like to pass the size of the text(length) back to the client and display it somewhere on the web page asynchronously. But failed... Here is my code:
HTML
<script type="text/javascript">
var render_text = function(csvFile, onLoadCallback){
var reader = new FileReader();
reader.onload = onLoadCallback;
reader.readAsText(csvFile);
}
$(document).ready(function(){
$("#id_csvFileInput").on("change", function(e){
render_text(this.files[0], function(e){
var text = e.target.result;
$.ajax({
url: "",
type: 'POST',
async: true,
data: {'text': text},
success: function(data){
$("#id_test").text(data.size);
}
});
});
});
});
</script>
<p>
<input type="file" name="csvFileInput" id="id_csvFileInput" accept=".csv">
</p>
<div>
<p>Waiting for reponse context....</p>
<span id="id_test">?</span>
</div>
View.py
# Home page.
#csrf_exempt
def home(request):
template = 'hbvapp/home.html'
context = {}
if request.method == "POST" and request.is_ajax():
context['test'] = request.POST.get('text')
context['size'] = len(context['test'])
print context['size']
return render(request, template, context)
else:
return render(request, template)
ANY HELP WILL BE DEEPLY APPRECIATED !
Reagards
try it
from django.http import JsonResponse
if request.method == "POST" and request.is_ajax():
context['test'] = request.POST.get('text')
context['size'] = len(context['test'])
print context['size']
return JsonResponse(context)
# ^^^^^
more details jsonresponse
you can send it this way also:
context['test'] = request.POST.get('text')
context['size'] = len(context['test'])
print context['size']
return HttpResponse(json.dumps(context), content_type='application/json')
and in you js you can access it like this:
success: function(data){
$("#id_test").text(data['size']);
}

display the UpdateView form on the same page as CreateView form in django

I want to display the UpdateView form on the same page as CreateView form so whenever "Edit" button is clicked the UpdateView form is displayed on the same page
<button type="button" class="edit_btn" data-url="{% url 'parts:stock_update_view' stock.id %}">Edit</button>
ajax for edit button:
$.ajax({
url: $(this).data('url'),
data: {
},
dataType: 'json',
success: function (data) {
alert(data.name);
}
});
}
});
class stock_update_view(UpdateView):
model = part_stock
fields = ['part_id','entry_date','supplier','amount','remaining']
success_url = reverse_lazy('parts:part_list')
template_name = 'part_detail.html'
def get_context_data(self, **kwargs):
context = super(stock_update_view, self).get_context_data(**kwargs)
context['update_form'] = context.get('form')
return context
def get(self, request, *args, **kwargs):
username = request.GET.get('username', None)
data = {
}
return JsonResponse(data)
I want to get back the UpdateView form as jsonResponse so that I can render it in my template.after returning context['update_form'] = context.get('form') will I be able to render the pre-filled form in my template if yes then how can I return it?
You can define get_initial() function like this:
def get_initial(self):
initial = {
'part_id' : self.request.user.part_id
'entry_date: self.....
}
return initial
This function will pre-populate the form which you are passing in the context.

Django, jquery, and modelforms

Looking to get some insight and tips on using ajax with django.
Say I have a function:
def add_comment(request, pk):
if request.method == 'POST' and request.is_ajax():
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = comment_form.save(commit=True)
comment.save()
json = simplejson.dumps(comment, ensure_ascii=False)
return HttpResponse(json, mimetype='application/json')
return render_to_response({{ post.id }}', {'comment': comment,}), context_instance=RequestContext(request), mimetype='application/json')
and I'm trying to post the comments to a page without a redirect with ajax function:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
$(document).click(function()
{
$('#comment_form').submit(function()
{
var dataString = $('#comment_form').serialize();
$.ajax({
type: 'POST',
url: '',
data: dataString,
success: function(data){
$('').html(data);
},
});
return false;
});
});
</script>
I believe I'm mixing up a few things here. I am trying to get the page to load comments without a redirect. I don't need an exact answer, maybe just steered in the right direction.
This can helps:
this could be your view:
import json
def add_comment(request, pk):
if request.method == 'POST' and request.is_ajax():
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = comment_form.save(commit=True)
comment.save()
json_response = json.dumps({"status":"Success"})
return HttpResponse(json_response)
errors = {}
for k, v in job_type_form.errors.items():
errors[k.capitalize()] = v
response = {
'success': False,
'errors': errors
}
return HttpResponse(json.dumps(response))
and your jquery could be like this:
$('#comment_form').submit(function() {
var dataString = $('#comment_form').serialize();
$.ajax({
type: 'POST',
url: '',// you need to put this to something like '{% url to_your_view %}'
data: dataString,
dataType: 'json'
success: function(data){
// you can access to your json object like data.status or data.something
$('').html(data.status);
},
});
return false;
});
Thanks for the posts I finally got things worked out. The jquery was the main issue.
$(document).ready(function() {
$('#comment_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url art.views.post %}',
data: $('#comment_form').serialize(),
dataType: 'json';
success: function(){
location.reload();
$('#comment_form').get(0).reset();
},
});
return false;
});
});
I was sending the DOM object not the actual form data to the view.
In the view I combined two functions to get the two sharing the same URL.
def post(request, pk):
post = Post.objects.get.(pk=int(pk))
comments = Comment.objects.filter(post=post)
_dict = dict(post=post, comments=comments, form=Comment_form(), user=request.user)
_dict.update(csrf(request))
cf_obj = Comment(post = Post.objects.get(pk=pk))
if request.method == 'POST' and request.is_ajax():
if comment_form.is_valid():
comment = comment_form.save(commit=True)
else:
raise Http404
response = serializers.serialize('json', [comment])
return HttpResponse(response, mimetype='application/json')
return render_to_response('post.html', d)

Resources