英文:
Submit form with only two clicks on Submit Django
问题
在你的HTML代码中,你尝试通过JavaScript来模拟在一次点击中获取两次点击的效果,但似乎没有解决你的问题。这是因为你的JavaScript代码中存在一些问题。我会提供一些建议来改进你的JavaScript代码,以确保在一次点击中提交表单并切换表单。
在你的JavaScript代码中,你可以使用setTimeout
函数来添加延迟,然后在延迟后切换表单和显示下一个块。在这里是一些修订后的JavaScript代码:
<script>
const submitButton = document.querySelector('.button');
const nextBlock = document.querySelector('.next-block');
nextBlock.style.display = 'none'; // 隐藏下一个块
submitButton.addEventListener('click', (event) => {
event.preventDefault(); // 阻止表单提交
submitButton.disabled = true; // 禁用提交按钮以防止多次点击
// 在一次点击后添加延迟
setTimeout(() => {
nextBlock.style.display = 'block'; // 显示下一个块
submitButton.style.display = 'none'; // 隐藏提交按钮
}, 200);
});
</script>
这个修改后的代码会在点击提交按钮后禁用按钮,然后添加一个短暂的延迟,之后显示下一个块并隐藏提交按钮,以模拟在一次点击中执行两个操作。
请确保在你的HTML文件中正确包含这段JavaScript代码,并检查是否有其他可能引起问题的因素,例如CSS样式或其他JavaScript代码。希望这个修改能够帮助你解决问题。
英文:
I created a page with questions to the phone, I need that when, when a person clicks on the submit form, he must submit the form with one click, and change the same form with one click too.
But for now, it can be done with just two mouse clicks.
my models.py:
class Items_buy(models.Model):
class Meta:
db_table = 'items_buy'
verbose_name = 'Телефон который покупаем'
verbose_name_plural = 'Телефоны которые покупаем'
image_phone = ResizedImageField(size=[100,100], upload_to='for_sell/',verbose_name='Фотография модели телефона')
model_produkt = models.TextField(max_length=80, verbose_name='Модель продукта ')
text = models.TextField(max_length=500, verbose_name='Текст')
max_prise = models.FloatField(verbose_name='Максимальная цена telefoha')
image_phone_for_buy_bord = ResizedImageField(size=[100,100],upload_to='for_sell/',verbose_name='Фотография модели телефона ha prodazy')
def __str__(self):
return self.model_produkt
class Question(models.Model):
class Meta:
db_table = 'question'
verbose_name = 'Вопрос к телефону'
verbose_name_plural = 'Вопросы к телефону'
items_buy = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
titles= models.CharField(max_length=150,verbose_name='Заголовок вопросa')
question_text =models.TextField(max_length=100, verbose_name='Заголовок вопросa text')
#max_prise_qustion = models.FloatField(verbose_name='Максимальная цена')
def __str__(self):
return self.titles
class Choice(models.Model):
class Meta:
db_table = 'choice'
verbose_name = 'Выбор ответа'
verbose_name_plural = 'Выбор ответов'
question = models.ForeignKey(Question, on_delete=models.RESTRICT,related_name="options")
title = models.CharField(max_length=1000, verbose_name='Заголовок выбора')
price_question = models.FloatField(verbose_name='Цена ответа')
#lock_other = models.BooleanField(default=False, verbose_name='Смотреть другой вариант ответа')
def __str__(self):
return str(self.price_question)
class Answer(models.Model):
class Meta:
db_table = 'answer'
verbose_name = 'Ответ на вопрос'
verbose_name_plural = 'Ответы на вопросы'
items_buy = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
question = models.ForeignKey(Question, on_delete=models.RESTRICT)
choice = models.ForeignKey(Choice, on_delete=models.RESTRICT)
#created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.items_buy)
my forms.py:
class AnswersForm(forms.Form):
def __init__(self, *args, instance: Items_buy, **kwargs):
self.instance = instance
super().__init__(*args, **kwargs)
questions = Question.objects.filter(items_buy_id=instance)
existing_answers = {
question_id: choice_id
for question_id, choice_id in Answer.objects.filter(
items_buy=self.instance
).values_list("question_id", "choice_id")
}
for question in questions:
self.fields["question_%s" % question.id] = forms.ChoiceField(
help_text=mark_safe(question.titles),
label=mark_safe(question.question_text),
choices=question.options.all().values_list("id", "title"),
widget=forms.RadioSelect(attrs={"class": "form-check-input"}),
)
self.fields["question_%s" % question.id].initial = {} #existing_answers.get(
#question.id, None
#)
def save(self):
answers_to_create = []
for field, value in self.cleaned_data.items():
if field.startswith("question_"):
question_id = field.split("_")[-1]
answers_to_create.append(
Answer(
items_buy=self.instance,
question_id=question_id,
choice_id=value,
)
)
Answer.objects.filter(items_buy=self.instance).delete()
Answer.objects.bulk_create(answers_to_create)
my views.py:
def getqestionses(request, pk):
iphone = get_object_or_404(Items_buy, pk = pk)
total_score = iphone.answer_set.all().aggregate(total_score=Sum("choice__price_question"))["total_score"]
form = AnswersForm(request.POST or None, instance=iphone)
if form.is_valid():
form.save()
return render(request, "getqestionses.html", {'form': form, 'total_score':total_score, 'iphone':iphone})
my HTML:
<!DOCTYPE html>
{% load static %}
{% load widget_tweaks %}
{% block content %}
<head>
<link rel="stylesheet" href="{% static 'css/qestionses.css' %}" type="text/css">
</head>
<body>
{% include 'navbar.html' %}
<div class="div">
<h1>{{ iphones.model_produkt }}</h1>
<form method="post">
<div class="ded">
{% csrf_token %}
{% for field in form %}
<div class="qestion">
{{ field.label_tag}}
</div>
<div class="help_text">
{{ field.help_text }}
</div>
<div class="form-check">
{% for radio in field %}
{{ radio.tag }}
<div class="chack-button">
{{ radio.choice_label }}
</div>
{% endfor %}
</div>
{% endfor %}
<button type="submit" class="button">Submit</button>
</form>
</div>
<div class="next-block">
<h1> {{ total_score }} </h1>
<form action="{% url 'orderforsel' iphone.id %}">
<button class="button-next-block">next page for order create</button>
</form>
</div>
</div>
<script>
const submitButton = document.querySelector('.button');
const nextBlock = document.querySelector('.next-block');
nextBlock.style.display = 'none'; // hide the next-block div initially
submitButton.addEventListener('click', (event) => {
event.preventDefault(); // prevent the form from submitting
// Simulate a double click by waiting for a short delay before displaying the next-block div
setTimeout(() => {
nextBlock.style.display = 'block';
submitButton.style.display = 'none';
}, 200);
});
</script>
</body>
{% include 'info.html' %}
{% include 'end_navbar.html' %}
{% endblock %}
I tried adding a script to get 2 clicks in one click but unfortunately that didn't change my issue.
答案1
得分: 0
这不必那么复杂。Javascript有一个dblclick
事件。
https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event
这将允许您轻松捕获双击事件。
英文:
It does not have to be this complicated. Javascript has a dblclick
event.
https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event
This will allow you to easily capture doubleclicks
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论