view function is not being executed - javascript

I was trying to make a basic banking system using Django, in which a user can transfer money to other user. But when I tried to transfer money nothing happens, probably because transfer function in views.py is not being executed.
Here are transaction.html file and transfer function from views.py :
transaction.html
{% extends 'bank/base.html' %}
{% block content %}
<div class="container">
<h2>Transfer Money</h2>
<form action="{% url 'transaction' %}" method="post">
{% csrf_token %}
<label for="s_acc">Select sender details</label>
<select name="s_acc" required>
<option value="select">Select</option>
{% for cust in customer %}
<option value="{{cust.account_number}}">{{cust.name}}: {{cust.account_number}} : {{cust.balance}}</option>
{% endfor %}
</select>
<br>
<label for="amt">Enter amount</label>
<input type="number" name="amt" required>
<br>
<label for="r_acc">Select receiver details</label>
<select name="r_acc" required>
<option value="select">Select</option>
{% for cust in customer %}
<option value="{{cust.account_number}}">{{cust.name}}: {{cust.account_number}} : {{cust.balance}}</option>
{% endfor %}
</select>
<br>
<button type="submit" name="button">TRANSFER</button>
</form>
</div>
{% endblock %}
transfer function from views.py:
def Transfer(request):
customer = Customer.objects.all();
if request.method=="POST":
s_acc = request.POST.get('s_acc')
amt = request.POST.get('amt')
r_acc = request.POST.get('r_acc')
print(s_acc)
print(amt)
print(r_acc)
amt = int(amt)
if((s_acc=='select')or(amt=='select')or(r_acc=='select')or(s_acc==r_acc)):
messages.warning(request,"Account not selected or both the accounts are same")
elif(amt<=0):
messages.warning(request,"Enter valid amount")
else:
for c in customer:
if(c.account_number == s_acc):
s_name = c.name;
if(amt>c.balance):
messages.warning(request,"Insufficient balance")
break
for x in customer:
if(x.account_number == r_acc):
r_name = x.name
r_bal = x.balance
break;
for c in customer:
if c.account_number == s_acc and r_acc!=s_acc and r_acc!= 'select' and amt<=c.balance and amt>0:
q1 = Transaction(sender_name = s_name, amount = amt, receiver_name = r_name )
q1.save()
acc_bal = c.balance - amt
q2 = Customer.objects.filter(account_number = s_acc).update(balance = acc_bal)
q2.save()
acc_bal = r_bal+amt
q3 = Customer.objects.filter(account_number = r_acc).update(balance = acc_bal)
q3.save()
messages.success(request,"Transfer Complete")
return redirect('tranfer_list')
return render(request,'bank/transaction.html',{'customer':customer})
urls.py
from django.urls import path
from bank import views
urlpatterns = [
path('',views.AboutView.as_view(),name = 'about' ),
path('about/', views.AboutView.as_view(),name = 'about'),
path('customers/', views.CustomerListView.as_view(),name = 'customer_list'),
path('transfer_list/', views.TransactionListView.as_view(), name = 'transfer_list'),
path('transaction/', views.Transfer, name = 'transaction'),
path('customers/new', views.CustomerCreateView, name = 'customer_new'),
]
Thanks in advance :)

Related

How can I use Ajax to display if username is already taken in django?

I'm trying to implement some code that will search if a username already exists and then display an error if it does dynamically rather than having to refresh the entire page. I tried implementing some JS and Ajax, but since I'm totally new to JS, it's not working and I'm not sure why. What am I doing wrong?
reg.html
{% extends "dating_app/base.html" %}
{% load bootstrap4 %}
{% block content %}
{% block javascript %}
<script>
$("#id_username").change(function () {
var username = $(this).val();
$.ajax({
url: '/ajax/check_if_username_exists_view/',
data: {
'username': username
},
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
});
</script>
{% endblock %}
<br>
<h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1>
<form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" >
<div class="is-valid">
{% bootstrap_form registration_form%}
</div>
{% csrf_token %}
{% for field in bootstrap_form %}
<p>
{{field.label_tag}}
{{field}}
{% if field.help_text %}
<small style="color:grey;">{{field.help_text}}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red;">{{error}}"</p>
{% endfor %}
</p>
{% endfor %}
<div class="form-check">
<input type="checkbox" id="accept-terms" class="form-check-input">
<label for="accept-terms" class="form-check-label">Accept Terms & Conditions</label>
</div>
<div>
<br>
<button type="submit">Register</button>
</div>
</form>
{% endblock content %}
views.py/
def check_if_username_exists_view(request):
username = request.GET.get('username', None)
data = {
'is_taken': User.objects.filter(username__iexact=username).exists()
}
return JsonResponse(data)
urls.py/
path('ajax/check_if_username_exists_view/', views.check_if_username_exists_view, name='check_if_username_exists_view'),
models.py/
Class ProfileManager(BaseUserManager):
def create_user(self, username, email,description,photo, password=None):
if not email:
raise ValueError("You must creat an email")
if not username:
raise ValueError("You must create a username!")
if not description:
raise ValueError("You must write a description")
if not photo:
raise ValueError("You must upload a photo")
user = self.model(
email=self.normalize_email(email),
username = username,
description= description,
photo= photo,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email,description,photo, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
description=description,
photo=photo,
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
class Profile(AbstractBaseUser):
class Meta:
swappable = 'AUTH_USER_MODEL'
email = models.EmailField(verbose_name="email")
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
#what I added
description = models.TextField()
photo = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
matches = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='+', blank=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['description','photo','email']
objects = ProfileManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self,app_label):
return True
So, in my base.html, which registration.html is inheriting from, I had 2 lines at the bottom of that page that were javascript lines that were not allowing Ajax to work because they were overriding the code I had in my registration.html. Once I removed them they started working.
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery-slim.min.js"><\/script>')</script>

Why is my Javascript not working for checking is Username already exists?

I am super new to Javascript, and I'm trying to implement some code that will search if a username already exists and then display an error if it does dynamically rather than having to hit submit and then finding out the username already existed. I tried implementing some JS but it's not working. What am I doing wrong?
reg.html
{% extends "dating_app/base.html" %}
{% load bootstrap4 %}
{% block content %}
{% block javascript %}
<script>
$("#id_username").change(function () {
var username = $(this).val();
$.ajax({
url: '/ajax/check_if_username_exists_view/',
data: {
'username': username
},
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
});
</script>
{% endblock %}
<br>
<h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1>
<form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" >
<div class="is-valid">
{% bootstrap_form registration_form%}
</div>
{% csrf_token %}
{% for field in bootstrap_form %}
<p>
{{field.label_tag}}
{{field}}
{% if field.help_text %}
<small style="color:grey;">{{field.help_text}}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red;">{{error}}"</p>
{% endfor %}
</p>
{% endfor %}
<div class="form-check">
<input type="checkbox" id="accept-terms" class="form-check-input">
<label for="accept-terms" class="form-check-label">Accept Terms & Conditions</label>
</div>
<div>
<br>
<button type="submit">Register</button>
</div>
</form>
{% endblock content %}
views.py/check_if_username_exists_view
def check_if_username_exists_view(request):
username = request.GET.get('username', None)
data = {
'is_taken': User.objects.filter(username__iexact=username).exists()
}
return JsonResponse(data)
urls.py/check_if_username_exists_view
path('ajax/check_if_username_exists_view/', views.check_if_username_exists_view, name='check_if_username_exists_view'),
models.py
Class ProfileManager(BaseUserManager):
def create_user(self, username, email,description,photo, password=None):
if not email:
raise ValueError("You must creat an email")
if not username:
raise ValueError("You must create a username!")
if not description:
raise ValueError("You must write a description")
if not photo:
raise ValueError("You must upload a photo")
user = self.model(
email=self.normalize_email(email),
username = username,
description= description,
photo= photo,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email,description,photo, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
description=description,
photo=photo,
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
class Profile(AbstractBaseUser):
class Meta:
swappable = 'AUTH_USER_MODEL'
email = models.EmailField(verbose_name="email")
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
#what I added
description = models.TextField()
photo = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
matches = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='+', blank=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['description','photo','email']
objects = ProfileManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self,app_label):
return True

IntegrityError at /accounts/regist_save/ happens

IntegrityError at /accounts/regist_save/
NOT NULL constraint failed: accounts_newuser.user_id
error happens .I wrote in
views.py
def regist(request):
regist_form = RegisterForm(request.POST or None)
profile_form = ProfileForm(request.POST or None)
context = {
'regist_form': regist_form,
'profile_form': profile_form,
}
return render(request, 'registration/regist.html', context)
#require_POST
def regist_save(request):
regist_form = RegisterForm(request.POST or None)
profile_form = ProfileForm(request.POST or None)
if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid():
regist = regist_form.save(commit=False)
regist.is_staff = True
regist.save()
profile = profile_form.save(commit=False)
sex = request.POST.get("sex", "")
print(1111)
print(sex)
profile.save()
else:
print(regist_form.errors)
print(profile_form.errors)
return redirect('detail')
regist.html
<div class="form-group-lg">
<label for="id_username">Username</label>
{{ regist_form.username }}
</div>
<div class="form-group-lg">
<label for="id_email">Email</label>
{{ regist_form.email }}
</div>
<div class="form-group-lg">
<label for="id_password">Password</label>
{{ regist_form.password1 }}
</div>
<div class="form-group-lg">
<label for="id_password">Password2</label>
{{ regist_form.password2 }}
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
{% load static %}
<div class="form-group-lg">
<label for="birthday">Date</label>
<select id="year" class="form-control year" name="year">
<option value="">--</option>
</select>
Year
<select id="month" class="form-control month" name="month">
<option value="">--</option>
</select>
Month
<select id="day" class="form-control day" name="day">
<option value="">--</option>
</select>
Day
<br>
<br>
</div>
<div class="form-group-lg">
<label for="sex">SEX</label>
<select id="sex" class="form-control sex" name="sex">
<option value="">--</option>
<option value="male">male</option>
<option value="female">female</option>
</select>
</div>
<script src="{% static 'accounts/register.js' %}"></script>
<button type="submit" class="btn-lg regist">REGIST</button>
<input name="next" type="hidden" />
{% csrf_token %}
</form>
regist.js
$(() => {
for (let i = 1900; i < 2020; i++) {
$("#year").append(`<option value="${i}">${i}</option>`);
}
for (let i = 1; i < 12; i++) {
$("#month").append(`<option value="${i}">${i}</option>`);
}
for (let i = 1; i < 31; i++) {
$("#day").append(`<option value="${i}">${i}</option>`);
}
})
models.py
from django.db import models
from django.contrib.auth.models import User
class NewUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthday = models.CharField(max_length=100,null=True, blank=True, default=None)
sex = models.CharField(max_length=100,null=True, blank=True, default=None)
in forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User
from .models import NewUser
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email','password1','password1',)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['email'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
class ProfileForm(forms.ModelForm):
class Meta:
model = NewUser
fields = (
"birthday", "sex"
)
I really cannot understand why this error happens because I did not write user_id in NewUser models.I think Integrity Error means columns cannot be found in Model.OneToOneField can be connected withUser and NewUser's model .I think this error means I should prepare user_id in New User model but if my thinking is right, I cannot understand why.How should I fix this?What should I write it?
This happens because in the NewUser model, the user field is a required field. In the ProfileForm the user field is not included. So when the ProfileForm tries to save the NewUser without user attached to it, it results in the above mentioned error.
What we have to do is to attach the user to the instance before actual save happens:
profile = profile_form.save(commit=False)
profile.user = registered_user # you can get the user from the registerform above
profile.save()

Change status in ajax on selectbox

I have a question, So ,this code work fine only for the first select box and I dont understand why. For first select box update on database work fine but If I tried to change the statut for the second select box the status remain unchanged. Can you help me? Sorry for my english
My view :
{% for gift in aFilterGifts %}
<form action="" id="updateStatus" method="post">
<select id="statusSelect"
name="{{ gift.id }}"
class="form-control"
onChange="updateCadeauStatus({{ gift.id }})">
{% for key,statut in form_logistique.statut.choices %}
<option value="{{ key }}"
{% if gift.etat == key %}selected="selected"{% endif %}>
{{ statut }}
</option>
{% endfor %}
</select>
</form>
{% endfor %}
<script>
function updateCadeauStatus(id) {
var id = id;
var selectedName = $("#statusSelect option:selected").val();
var url_deploy = 'http:localhost/updateStatus'
console.log(id);
console.log(selectedName);
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
});
}
</script>
The controller :
public function updateStatus(){
$iGiftId = $_POST['id_cadeau'];
$iNewStatus = $_POST['id_status'];
$bUpdate = $this->updateStatusByGiftId($iGiftId, $iNewStatus);
}
The model :
public static function updateStatusByGiftId($iGiftId, $iStatusId){
$request = sprintf( ' UPDATE `%s` set etat = %d WHERE id_instant_gagnant = %d ', $table, $iStatusId, $iGiftId);
return Mysqli::query($request, $database);
}
Thx in advance.
All your select boxes do have the same id id="statusSelect".
That's not valid HTML.
One solution would be to append the gift id to the id tag to create unique ids:
{% for gift in aFilterGifts %}
<form action="" id="updateStatus{{ gift.id }}" method="post">
<select id="statusSelect{{ gift.id }}"
name="{{ gift.id }}"
...
and for the script:
<script>
function updateCadeauStatus(id) {
var id = id,
selectedName = $("#statusSelect" + id + " option:selected").val(),
url_deploy = 'http:localhost/updateStatus';
console.log(id);
...

Hide variants that aren't available in Shopify?

Right now in default Shopify no matter what you select on style you'll still be able to choose any of those sizes even if it's not available for that style. I followed the instructions here: http://wiki.shopify.com/Linked_Options
It works great except that the second option list has duplicated items in it. Any idea why? here is what I have on my product-form.liquid. You can see it in action on my site here: http://gravitypicks.myshopify.com/collections/picks/products/axis
{% if product.available %}
<form action="/cart/add" method="post" class="clearfix product_form shappify_add_to_cart_form" enctype="multipart/form-data" data-money-format="{{ shop.money_format }}" data-shop-currency="{{ shop.currency }}" id="product-form-{{ product.id }}">
{% if settings.display_inventory_left %}
<div class="items_left">
{% if product.variants.first.inventory_management == "shopify" and product.variants.first.inventory_quantity > 0 %}
<p><em>{{ product.variants.first.inventory_quantity }} {{ settings.inventory_left_text | escape }}</em></p>
{% endif %}
</div>
{% endif %}
{% if product.options.size > 1 %}
<div class="select">
<select id="product-select-{{ product.id }}" name='id'>
{% for variant in product.variants %}
<option {% if variant == product.selected_or_first_available_variant %}selected="selected"{% endif %} value="{{ variant.id }}">{{ variant.title }}</option>
{% endfor %}
</select>
</div>
{% elsif product.options.size == 1 and (product.variants.size > 1 or product.options[0] != "Title") %}
<div class="select">
<label>{{ product.options[0] }}:</label>
<select id="product-select-{{ product.id }}" name='id'>
{% for variant in product.variants %}
<option {% if variant == product.selected_or_first_available_variant %}selected="selected"{% endif %} value="{{ variant.id }}">{{ variant.title }}</option>
{% endfor %}
</select>
</div>
{% else %}
<input type="hidden" name="id" value="{{ product.variants.first.id }}" />
{% endif %}
<!-- Bold Apps: Product Options -->
{% include 'shappify-options' %}
{% if settings.display_product_quantity %}
<div class="left">
<label for="quantity">Quantity:</label>
<input type="number" min="1" size="2" class="quantity" name="quantity" id="quantity" value="1" />
</div>
{% endif %}
<div class="purchase clearfix {% if settings.display_product_quantity %}inline_purchase{% endif %}">
{% if settings.cart_return == 'back' %}
<input type="hidden" name="return_to" value="back" />
{% endif %}
<input type="submit" name="add" value="{{ settings.add_to_cart_text | escape }}" class="action_button add_to_cart" />
</div>
</form>
{% if product.variants.size > 1 or product.options.size > 1 %}
<script type="text/javascript">
// <![CDATA[
$(function() {
$product = $('#product-' + {{ product.id }});
new Shopify.OptionSelectors("product-select-{{ product.id }}", { product: {{ product | json }}, onVariantSelected: selectCallback{% if product-form == 'product' %}, enableHistoryState: true{% endif %} });
{% if product.available and product.options.size > 1 %}
Shopify.linkOptionSelectors({{ product | json }});
{% endif %}
});
// ]]>
</script>
{% endif %}
{% endif %}
Here is the JS that is on the page:
<script>
// (c) Copyright 2014 Caroline Schnapp. All Rights Reserved. Contact: mllegeorgesand#gmail.com
// See http://docs.shopify.com/manual/configuration/store-customization/advanced-navigation/linked-product-options
var Shopify = Shopify || {};
Shopify.optionsMap = {};
Shopify.updateOptionsInSelector = function(selectorIndex) {
switch (selectorIndex) {
case 0:
var key = 'root';
var selector = jQuery('.single-option-selector:eq(0)');
break;
case 1:
var key = jQuery('.single-option-selector:eq(0)').val();
var selector = jQuery('.single-option-selector:eq(1)');
break;
case 2:
var key = jQuery('.single-option-selector:eq(0)').val();
key += ' / ' + jQuery('.single-option-selector:eq(1)').val();
var selector = jQuery('.single-option-selector:eq(2)');
}
var initialValue = selector.val();
selector.empty();
var availableOptions = Shopify.optionsMap[key];
for (var i=0; i<availableOptions.length; i++) {
var option = availableOptions[i];
var newOption = jQuery('<option></option>').val(option).html(option);
selector.append(newOption);
}
jQuery('.swatch[data-option-index="' + selectorIndex + '"] .swatch-element').each(function() {
if (jQuery.inArray($(this).attr('data-value'), availableOptions) !== -1) {
$(this).removeClass('soldout').show().find(':radio').removeAttr('disabled','disabled').removeAttr('checked');
}
else {
$(this).addClass('soldout').hide().find(':radio').removeAttr('checked').attr('disabled','disabled');
}
});
if (jQuery.inArray(initialValue, availableOptions) !== -1) {
selector.val(initialValue);
}
selector.trigger('change');
};
Shopify.linkOptionSelectors = function(product) {
// Building our mapping object.
for (var i=0; i<product.variants.length; i++) {
var variant = product.variants[i];
if (variant.available) {
// Gathering values for the 1st drop-down.
Shopify.optionsMap['root'] = Shopify.optionsMap['root'] || [];
Shopify.optionsMap['root'].push(variant.option1);
Shopify.optionsMap['root'] = Shopify.uniq(Shopify.optionsMap['root']);
// Gathering values for the 2nd drop-down.
if (product.options.length > 1) {
var key = variant.option1;
Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
Shopify.optionsMap[key].push(variant.option2);
Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
}
// Gathering values for the 3rd drop-down.
if (product.options.length === 3) {
var key = variant.option1 + ' / ' + variant.option2;
Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
Shopify.optionsMap[key].push(variant.option3);
Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
}
}
}
// Update options right away.
Shopify.updateOptionsInSelector(0);
if (product.options.length > 1) Shopify.updateOptionsInSelector(1);
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
// When there is an update in the first dropdown.
jQuery(".single-option-selector:eq(0)").change(function() {
Shopify.updateOptionsInSelector(1);
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
});
// When there is an update in the second dropdown.
jQuery(".single-option-selector:eq(1)").change(function() {
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
});
};
</script>
This link here helped immensely. I had to do some tweaking to fit my uses but it was 99% there for me.
http://docs.shopify.com/manual/configuration/store-customization/advanced-navigation/linked-product-options

Categories