I have two datalist input like this.
<input list="Province" name="Province" id="1">
<datalist id="Province">
{% for item in province_list %}
<option >{{item.Name}}</option>
{% endfor %}
</datalist>
<input list="City" name="City" id="2">
<datalist id="City">
{% for item in city_list %}
<option >{{item.Name}}</option>
{% endfor %}
</datalist>
i want when user select Province, i show list of that province city in input2.
I use JavaScript as below:
$("input[name=Province]").on('input', function () {
province = $(this).val();
dataList.empty();
$.ajax({
url: "/get_cars_"+province,
dataType: 'json',
success: function (data) {
console.log(data);
for (var i = 0, len = data.length; i < len; i++) {
$("input[name=City]").append("<option value='" +
data[i].city + "'></option>");
}
},
error: function (req, status, err) {
console.log('something went wrong', status, err);
}
});
});
In server side handle "/get_cities_\w+" request.
Remove second "for" statement in html code:
<datalist id="City">
</datalist>
Server side code in Django:
def getTheVendorProducts(request):
if request.is_ajax():
try:
uriQueri = request.build_absolute_uri()
province = uriQueri.split('_')[]
province = urllib.parse.unquote(province.split('?')[0])
vendorProduct= getTheCitiesOfprovince(province)
return HttpResponse(convertListToJson(vendorProduct), 'application/json')
except Exception as e:
logging.error(e)
return failedHttpResponse()
You need to define your own "getTheCitiesOfprovince" and "convertListToJson" functions. Visit here For more information about this type questions.
Related
I asked this question previously and didn't get any help/solution. So I'm asking again.
I'm trying to make sure that even if the user refresh the page or goes back and comes back to that page, the radio button is still the same as what the user selects.
N.B: the value of the radio button is saved in sessions
<div class="col-md-1 ps-md-1">
<input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}"
value="{{option.id}}">
</div>
Ajax
$('input[type=radio][name=deliveryOption]').on('change', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "checkout:cart_update_delivery" %}',
data: {
deliveryoption: $(this).val(),
csrfmiddlewaretoken: "{{csrf_token}}",
action: "post",
},
success: function (json) {
document.getElementById("total").innerHTML = json.total;
document.getElementById("delivery_price").innerHTML = json.delivery_price;
},
error: function (xhr, errmsg, err) {},
});
});
my view
def cart_update_delivery(request):
cart = Cart(request)
if request.POST.get("action") == "post":
delivery_option = int(request.POST.get("deliveryoption"))
delivery_type = DeliveryOptions.objects.get(id=delivery_option)
updated_total_price = cart.cart_update_delivery(delivery_type.delivery_price)
session = request.session
if "purchase" not in request.session:
session["purchase"] = {
"delivery_id": delivery_type.id,
}
else:
session["purchase"]["delivery_id"] = delivery_type.id
session.modified = True
response = JsonResponse({"total": updated_total_price, "delivery_price": delivery_type.delivery_price})
return response
when I added a django templating if statement, it kinda work but the radio button is always remember on the last radio button when refreshed.
{% for option in deliveryoptions %}
<input class="align-middle h-100" type="radio" {% if deliveryoption == %} checked=1 {% elif delivery_option == 2 %} checked="checked"{% endif %} autocomplete='on' name="deliveryOption" id="{{option.id}}"
value="{{option.id}}">
</div>
</div>
</div>
{% endfor %}
</div>
I am trying to build a dependant dropdown in a django form, but it is not working. I have followed videos and tutorials, but got no luck.
I would like to select a brand of a car (make) and then a model of a car. The model depends on the car's brand, of course.
I have followed this tutorial https://python.plainenglish.io/python-and-django-create-a-dependent-chained-dropdown-select-list-b2c796f5a11
Status: The "Make" dropdown works fine. The "Model" dropdown is never showing anything.
It just does not work, but no error is shown... :S
models.py
from django.db import models
from django import forms
class Vehicle(models.Model):
make = forms.CharField(max_length=30)
model = forms.CharField(max_length=30)
...omitted
forms.py
from django import forms
from .models import Vehicle
import json
def readJson(filename):
with open(filename, 'r') as fp:
return json.load(fp)
def get_make():
""" GET MAKE SELECTION """
filepath = '/Users/alvarolozanoalonso/desktop/project_tfm/tfm/JSON/make_model_A.json'
all_data = readJson(filepath)
all_makes = [('-----', '---Select a Make---')]
for x in all_data:
if (x['make_name'], x['make_name']) in all_makes:
continue
else:
y = (x['make_name'], x['make_name'])
all_makes.append(y)
# here I have also tried "all_makes.append(x['make_name'])
return all_makes
class VehicleForm(forms.ModelForm):
make = forms.ChoiceField(
choices = get_make(),
required = False,
label='Make:',
widget=forms.Select(attrs={'class': 'form-control', 'id': 'id_make'}),
)
...omitted
class Meta:
model = Vehicle
fields = ['make', 'is_new', 'body_type', 'fuel_type', 'exterior_color', 'transmission', 'wheel_system', 'engine_type',
'horsepower', 'engine_displacement', 'mileage', 'transmission_display', 'year', 'fuel_tank_volume',
'city_fuel_economy', 'highway_fuel_economy', 'maximum_seating']
model.HTML
{% block javascript %}
<script>
$("#id_make").change(function () {
var makeId = $(this).val();
$.ajax({
type: "POST",
url: "{% url 'get-model' %}",
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'make': makeId,
},
success: function (data) {
console.log(data.models);
let html_data = '<option value="">-------</option>';
data.models.forEach(function (data) {
html_data += `<option value="${data}">${data}</option>`
});
$("#id_model").html(html_data);
}
});
});
</script>
{% endblock javascript %}
<form class="" action="" method="post">
{% csrf_token %}
{% for error in errors %}
<div class="alert alert-danger mb-4" role="alert">
<strong>{{ error }}</strong>
</div>
{% endfor %}
<div class="form-row">
<div class="form-group col-md-6">
<label>Status:</label>
{{ form.make }}
</div>
<div class="form-group col-lg-6">
<label >Model:</label>
<select id="id_model" class="form-control" name="state">
<option value="-----">Select Model</option>
</select>
</div>
...omitted
<div class="form-group col-md-6">
<button type="submit" class="btn btn-primary">Calculate</button>
</div>
</form>
views.py
def model(request):
context = {}
if request.method == 'GET':
form = VehicleForm()
context['form'] = form
return render(request, 'model.html', context)
if request.method == 'POST':
form = VehicleForm(request.POST)
if form.is_valid():
return render(request, 'model.html', context)
def getModel(request):
make = request.POST.get('make')
models = return_model_by_make(make)
return JsonResponse({'models': models})
Your change handler for id_make is attached before the select is created in the DOM, so your event handler does not fire.
You can use event delegation to set up an event handler before an element is created
$(document).on('change', "#id_make", function () {
var makeId = $(this).val();
$.ajax({
type: "POST",
url: "{% url 'get-model' %}",
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'make': makeId,
},
success: function (data) {
console.log(data.models);
let html_data = '<option value="">-------</option>';
data.models.forEach(function (data) {
html_data += `<option value="${data}">${data}</option>`
});
$("#id_model").html(html_data);
}
});
});
i am working on a project in Django where users can comment on a post. How do i update the comment count of each post, when user comment on a post increases the count to 1. I tried adding the id to div's but nothing happened. How do i implement this?
Home Template:
<!-- Comment count post is an object of all post in homepage -->
<div class="col-4 col-md-4 col-lg-4" id="newfeeds-form">
<a href="{% url 'site:comments' post.id %}" class="home-comment-icon z-depth-0">
<img src="{{ '/static/' }}images/comment.png" width="19" height="19" alt="comment-icon">
{% if post.comments.all|length > 999 %}
<span class="font-weight-bold dark-grey-text" id="number-of-comments">
{{ post.comments.count|floatformat }}
</span>
{% else %}
<span class="font-weight-bold dark-grey-text" id="number-of-comments">
{{ post.comments.count }} Comment{{ post.comments.count|pluralize }}
</span>
{% endif %}
</a>
</div>
<!-- New Feeds Comment Form -->
<div id="newfeeds-form">
{% include 'ajax_newfeeds_comments.html' %}
</div>
Ajax submit comment:
$(document).ready(function() {
$('.feeds-form').on('submit', onSubmitFeedsForm);
$('.feeds-form .textinput').on({
'keyup': onKeyUpTextInput,
'change': onKeyUpTextInput // if another jquery code changes the value of the input
});
function onKeyUpTextInput(event) {
var textInput = $(event.target);
textInput.parent().find('.submit').attr('disabled', textInput.val() == '');
}
function onSubmitFeedsForm(event) {
event.preventDefault();
// if you need to use elements more than once try to keep it in variables
var form = $(event.target);
var textInput = form.find('.textinput');
var hiddenField = form.find('input[name="post_comment"]');
$.ajax({
type: 'POST',
url: "{% url 'site:home' %}",
// use the variable of the "form" here
data: form.serialize(),
dataType: 'json',
beforeSend: function() {
// beforeSend will be executed before the request is sent
form.find('.submit').attr('disabled', true);
},
success: function(response) {
// as a hint: since you get a json formatted response you should better us "response.form" instead of response['form']
$('#newfeeds-form' + hiddenField.val()).html(response.form);
// do you really want to reset all textarea on the whole page? $('textarea').val('');
textInput.val(''); // this will trigger the "change" event automatically
},
error: function(rs, e) {
console.log(rs.resopnseText);
},
complete: function() {
// this will be executed after "success" and "error"
// depending on what you want to do, you can use this in the "error" function instead of here
// because the "success" function will trigger the "change" event automatically
textInput.trigger('change');
}
});
}
});
If you are sure that a new comment will be created with each request, than you can do it with incrementing the count on your desired html element.
I have not worked with python or django so far, but have tried to optimize the code.
<!-- ... -->
<div class="col-4 col-md-4 col-lg-4" id="newfeeds-form">
<span class="font-weight-bold dark-grey-text" id="number-of-comments" data-number="{{ post.comments.count }}">
{% if post.comments.count > 999 %}
{{ post.comments.count|div:1000|floatformat:1 }}k Comments
{% else %}
{{ post.comments.count }} Comment{{ post.comments.count|pluralize }}
{% endif %}
</span>
</div>
<!-- ... -->
function onSubmitFeedsForm(event) {
// ...
$.ajax({
// ...
success: function(response) {
$('#newfeeds-form' + hiddenField.val()).html(response.form);
textInput.val('');
// how you can increment the value of the amount of comments
refreshNumberOfComments();
},
// ...
});
// ...
}
// ...
function refreshNumberOfComments() {
var numberOfCommentsElement = $('#number-of-comments');
var numberOfComments = parseInt(numberOfCommentsElement.data('number')) + 1;
numberOfCommentsElement.data('number', numberOfComments);
if (numberOfComments == 1) {
numberOfCommentsElement.text(numberOfComments + ' Comment');
} else if (numberOfComments > 999) {
numberOfCommentsElement.text((numberOfComments / 1000).toFixed(1) + 'k Comments');
} else {
numberOfCommentsElement.text(numberOfComments + ' Comments');
}
}
Another option is to give the request the information about the amount of comments.
So you could make it in jQuery like this example
$.ajax({
// ...
success: function(response) {]
$('#newfeeds-form' + hiddenField.val()).html(response.form);
textInput.val('');
// your server side script should implement a new field "number_of_comments"
refreshNumberOfComments(response.number_of_comments); // for this call the function above has to get a parameter
},
// ...
});
I have a Python function which returns different messages in different scenarios. I want to style different messages differently, but I don't know how to do it.
This is my function:
def checkans(request, spanish_id):
random_spanish_question = get_object_or_404(Spanish, pk=spanish_id)
query = request.GET.get('ans')
coreng = random_spanish_question.english_set.get()
if query == str(coreng):
message = {
'message' : "Correct!"
}
return JsonResponse(message)
else:
message = {
'message' : "Incorrect. The correct answer is " + str(coreng)
}
return JsonResponse(message)
This is the HTML page:
<div class="flexcontainer" style="justify-content: center;">
<div class="sectiontitle">Quiz time
</div>
<div class="question_card">
<div class="question_word">{{ random_spanish_question }}</div>
<div id="msg"></div>
<form action="/checkans/{{random_spanish_question.id}}/" method="get">{% csrf_token %}
<label for="ans">Answer:</label>
<input type="text" name="ans"autofocus autocomplete="off" id="ansfield"/>
<input type="submit" value="Submit"/ id="submitbtn">
</form>
<input type="submit" value="Skip"/>
<button onclick="location.reload();">Next</button>
</div>
</div>
And this is the JS and AJAX code:
$('form').on('submit', function(e){
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: 'GET',
url: url,
data: form.serialize(),
success: function(data){
$("#msg").html(data.message);
}
});
disable();
})
function disable(e){
$('#submitbtn').prop('disabled', true);
$('#ansfield').prop('disabled', true)
}
For example, I want to make the "Correct!" message green, while if it returns "Incorrect...", I want it to be red, and underline the answer, "str(coreng)". Please tell me how I can do it. Thanks in advance!
def checkans(request, spanish_id):
random_spanish_question = get_object_or_404(Spanish, pk=spanish_id)
query = request.GET.get('ans')
coreng = random_spanish_question.english_set.get()
if query == str(coreng):
message = {
'message' : "<span class=\"result-correct\">Correct!</span>"
}
return JsonResponse(message)
else:
message = { =
'message' : "<span class=\"result-incorrect\">Incorrect. The correct answer is " + str(coreng)</span>
}
return JsonResponse(message)
where those classes are defined in css:
.result-correct{
color:#00aa00; // or any shade of green you like
}
.result-incorrect{
color:#aa0000; // or any shade of red you like
}
I'm trying to create my own like button but I am encountering some issues.
The code use Ajax with Django and I am getting an error message but I don't know what is wrong.
here is the code, mostly inspired by this post.
article\models.py
class Article(models.Model):
user = models.ForeignKey(User, default='1')
titre = models.CharField(max_length=100, unique=True)
[... some unrelated models ...]
slug = models.SlugField(max_length=40)
likes = models.ManyToManyField(User, related_name="likes")
def __str__(self):
return self.titre
#property
def total_likes(self):
return self.likes.count()
article\urls.py
url(r'^like/$', views.like_button, name='like_button'),
article\views.py
#login_required(login_url='/user')
def like_button(request):
if request.method == 'POST':
user = request.user
id = request.POST.get('pk', None)
article = get_object_or_404(Article, pk=id)
if article.likes.filter(id=user.id).exists():
article.likes.remove(user)
else:
article.likes.add(user)
context = {'likes_count': article.total_likes}
return HttpResponse(json.dumps(context), content_type='application/json')
(As you can see I am trying to get the article id and not the slug)
article.html
<div>
{% for a in article %}
[... some unrelated html ...]
<input type="button" class="like" name="{{ a.id }}" value="Like" />
<p>count : {{ a.total_likes }}</p>
{% endfor %}
</div>
<script>
$('.like').click(function(){
$.ajax({
type: "POST",
url: "{% url 'like_button' %}",
data: {'pk': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response) {
alert('Company likes count is now ' + response.count_likes);
},
error: function(rs, e) {
alert(rs.responseText); #No Article matches the given query.
}
});
})
</script>
the error say that No Article matches the given query.
What should I change in order to make this work?
From your code I can see that "id="like" is used in a for loop so it make multiple buttons with same ID. ID must be unique
Tryto change id with class like
<div>
{% for a in article %}
[... some unrelated html ...]
<input type="button" class="like" name="{{ a.id }}" value="Like" />
<p>count : {{ a.total_likes }}</p>
{% endfor %}
</div>
<script>
$('.like').click(function(){
var pk = $(this).attr('name');
$.ajax({
type: "POST",
url: "{% url 'like_button' %}",
data: {'pk': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response) {
alert('Company likes count is now ' + response.count_likes);
},
error: function(rs, e) {
alert('Something went wrong.'); #getting this message.
}
});
})
</script>