如何在Django中保存javascript实现



我正在实现一个页面,它代表了当我在Django中选择选项时所选择的选项的信息。源代码是用来调整数量的。价格已实行依数量而定。我想把数量和价格部分保存在数据库中。如何做到这一点?

<form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}">
<div class="form-group row" style="margin-top: -5px">
<label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label>
<div class="col-sm-6" style="margin-left: -90px;">
<select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}">
<option value="none">옵션을 선택하세요.</option>
{% for option in option_object %}
{% if option.option_code.option_code.option_code == value.option_code %}
{%if option.product_code == product %}
<optgroup label="{{option.name}}">
{% for value in value_object %}
{% if value.option_code.option_code == option.option_code %}
{%if value.product_code == product %}
<option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option>
{% endif %}
{% endif %}
{% endfor %}
{% endif %}
{% endif %}
{% endfor %}
</optgroup>
</select>
</div>
<div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"></div>
</div>

脚本

<script>
$().ready(function() {
$("#optionSelect").change(function() {
var checkValue = $("#optionSelect").val();
var checkText = $("#optionSelect option:selected").text();
var product = $("#productname").text();
var price = parseInt($("#price").text());
var test = parseInt($(this).find(':selected').data('price'));
var hapgae = price + test
if (checkValue != "no") {
var whtml =
"            <div class="cart_table">n" +
"            <hr style='width: 300px; margin-bottom: 30px;'>" +
"            <p style='font-size: 17px;'>" + product + "</p>" +
"<p style='font-size: 13px; margin-top: -10px;  margin-bottom: 20px;'>" + checkText + "</p>" +
"             <span class="del_li_btn" style='float: right; margin-right: 30px;'><img src="https://tictoc-web.s3.ap-northeast-2.amazonaws.com/web/img/icon/btn_del_circle.svg" style='width: 80%;'></span>n" +
"            <ul class="cart_list">n" +
"                <li style='list-style:none; margin-left: -38px;'>n" +
"                    <div class="opt_info">n" +
"                        <strong style='display: none' class="price_unit">" + hapgae + "</strong>n" +
"                        <div class="price_btn">n" +
"                            <input type="button" value="-" class="minus_btn">n" +
"                            <input style='width: 15%;' type="text" value="0" class="number">n" +
"                            <input type="button" value="+" class="plus_btn">n" +
"                        </div>n" +
"                <div class="total_p" style='margin-top:30px; margin-left: -2px;'>n" +
"                    <p style="font-size: 18px;">가격<strong class="price_amount" style="font-size: 18px; color: #849160; margin-left: 180px;">" + 0 + "</strong>원n" +
"                </div>n" +
"                    </div>n" +
"                </li>n" +
"            </ul>" +
"            </div>" +
"n" +
"n" +
"        </div>"
;
$("#selectOptionList").append(whtml)
}
$(document).ready(function () {
$('.price_btn input[type="button"]').on('click', function () {
var $ths = $(this);
var $par = $ths.parent().parent();
var $obj = $par.find('input[type="text"]');
var val = $obj.val();
if ($ths.val() == '-') {
if (val > 1)
$obj.val(--val);
} else if ($ths.val() == '+') {
if (val < 30)
$obj.val(++val);
}
//수량 변경
var unit_amount = $par.find('.price_unit').text().replace(/[^0-9]/g, "");
var quantity = val;
pay_unit_func($par, unit_amount, quantity);
pay_total_func();
});
function pay_unit_func($par, unit_amount, quantity) {
//1번 단
var unit_total_amount = $par.find('.price_amount').text((unit_amount * quantity).toLocaleString());
}
function pay_total_func() {
//2번 단
var amount_total = 0;
var converse_unit = 0;
$('.cart_list li').each(function () {
converse_unit = $(this).find('.price_amount').text().replace(/[^0-9]/g, "");
amount_total = amount_total + (parseInt(converse_unit) || 0);
});
var total_amount_money = $('.cart_total_price').children().find('.item_price').text(amount_total.toLocaleString());
var total_total_price = $('.cart_total_price').children().find('.total_price').text(total_price.toLocaleString());
}
//개별 아이템 삭제
$(document).ready(function() {
$('.del_li_btn').on('click', function () {
var recent_delete_cnt = $('.del_btn .num').text();
var check_delete_ck = $(this).parent().find('div[class="price_btn"]');
if (check_delete_ck == true) {
recent_delete_cnt = recent_delete_cnt - 1;
$('.del_btn .num').text(recent_delete_cnt);
}
$(this).parent().remove();
pay_total_func();
});
});
});
});
});
</script>

forms.py

class ElementForm(forms.Form):
value_code = forms.ModelChoiceField(error_messages={'required': "옵션을 선택하세요."}, label="옵션", queryset=Value.objects.all())
class JoindetailForm(forms.Form):
quantity = forms.IntegerField(error_messages={'required': "1개 이상 선택 시 참여가 가능합니다."}, label="수량")
price = forms.IntegerField(error_messages={'required': "1개 이상 선택 시 참여가 가능합니다."}, label="가격")

views.py

def join_create(request, id):
current_category = None
designated = Designated.objects.all()
designated_object = Designated.objects.filter(rep_price='True')
value_p = Value.extra_cost
element = Element.objects.all()
join_detail = JoinDetail.objects.all()
value_object = Value.objects.all()
categories = Category.objects.all()
products = Product.objects.all()
if not request.user.is_authenticated:
return HttpResponseRedirect(reverse('zeronine:login'))
if request.method == "POST":
product = Product.objects.get(product_code=id)
join = Join()
join.product_code = product
join.username = request.user
join.save()
if request.method == "POST":
form = ElementForm(request.POST)
if form.is_valid():
element = Element()
element.designated_code = Designated.objects.get(product_code=id)
element.value_code = form.cleaned_data['value_code']
element.save()
else:
element = Element()
element.designated_code = Designated.objects.get(product_code=id)
element.value_code = None
element.save()
if request.method == "POST":
form = JoindetailForm(request.POST)
if form.is_valid():
join_detail = JoinDetail()
join_detail.join_code = join
join_detail.designated_code = Designated.objects.get(product_code=id)
join_detail.price = form.cleaned_data['price']
join_detail.save()
return render(request, 'zeronine/list.html', {'products': 'products',
'current_category': current_category,
'products': products,
'join_detail':join_detail,
'categories': categories,
'designated': designated})
return render(request, 'zeronine/list.html', {'products':'products',
'current_category': current_category,
'products': products,
'join_detail':join_detail,
'categories': categories,
'designated': designated})

return render(request, 'zeronine/detail.html', {'product':'product',
'designated': designated,
'element': element,
'join_detail':join_detail,
'value_p':value_p,
'designated_object':designated_object,
'value_object': value_object})

models.py

class Product(models.Model):
product_code = models.AutoField(primary_key=True)
username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username')
category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
benefit = models.TextField()
detail = models.TextField()
target_price = models.IntegerField()
start_date = models.DateField()
due_date = models.DateField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['product_code']
index_together = [['product_code', 'slug']]
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('zeronine:product_detail', args=[self.product_code, self.slug])
# 옵션(옵션코드, 옵션명, 상품코드(fk))
class Option(models.Model):
option_code = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
def __str__(self):
return self.name
class Meta:
ordering = ['option_code']
# 옵션값(옵션값코드, 옵션값명, 옵션코드(fk), 상품코드(fk))
class Value(models.Model):
value_code = models.AutoField(primary_key=True)
option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code')
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
name = models.CharField(max_length=32)
extra_cost = models.IntegerField()
def __str__(self):
return self.name
class Meta:
ordering = ['value_code']
# 옵션지정상품(옵션지정상품코드, 상품코드(fk), 가격, 참여수량)
class Designated(models.Model):
designated_code = models.AutoField(primary_key=True)
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
price = models.IntegerField()
rep_price = models.BooleanField(default=True)
class Meta:
ordering = ['designated_code']
def __str__(self):
return str(self.designated_code)
# 상품옵션구성(상품옵션구성코드, 옵션지정상품코드, 옵션값코드)
class Element(models.Model):
element_code = models.AutoField(primary_key=True)
designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code')
value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code', null=True, blank=True)
class Meta:
ordering = ['element_code']
def __str__(self):
return str(self.element_code)
# 참여(참여코드, 아이디(fk), 상품코드(fk), 수량)
class Join(models.Model):
join_code = models.AutoField(primary_key=True)
username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username')
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
part_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.join_code)
class Meta:
ordering = ['join_code']
#참여상세(참여상세코드, 수량, 가격, 참여코드, 옵션지정상품코드)
class JoinDetail(models.Model):
joindetail_code = models.AutoField(primary_key=True)
join_code = models.ForeignKey(Join, on_delete=models.CASCADE, db_column='join_code')
designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, null=True, blank=True, db_column='designated_code')
quantity = models.IntegerField()
price = models.IntegerField()
def __str__(self):
return str(self.joindetail_code)
class Meta:
ordering = ['joindetail_code']

我认为你可以使用request.POST.get(''),因为在你的html中,我没有看到JoindetailForm所以你的form = JoindetailForm(request.POST)将为空值,你可以试试这个:

您可以添加您的unit_amount * quantity输入值和类型是隐藏的:

<input type="hidden" name="price" value="">

在视图中使用request.POST.get('')获取隐藏值:

price = request.POST.get('price')

和使用对象。create优于Form():

JoinDetail.objects.create(price=price, quantity=quantity)

和你有很多if request.method == "POST":在第一,如果是POST它request.method将是POST,所以只是离开第一次将是很好,容易调试。

相关内容

  • 没有找到相关文章

最新更新