使用两次点击“提交”按钮提交Django表单。

huangapple go评论69阅读模式
英文:

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 = &#39;items_buy&#39;
        verbose_name = &#39;Телефон который покупаем&#39;
        verbose_name_plural = &#39;Телефоны которые покупаем&#39;

    image_phone = ResizedImageField(size=[100,100], upload_to=&#39;for_sell/&#39;,verbose_name=&#39;Фотография модели телефона&#39;)
    model_produkt = models.TextField(max_length=80, verbose_name=&#39;Модель продукта &#39;)
    text = models.TextField(max_length=500, verbose_name=&#39;Текст&#39;)
    max_prise = models.FloatField(verbose_name=&#39;Максимальная цена telefoha&#39;)
    image_phone_for_buy_bord = ResizedImageField(size=[100,100],upload_to=&#39;for_sell/&#39;,verbose_name=&#39;Фотография модели телефона ha prodazy&#39;)


    def __str__(self):
        return self.model_produkt

class Question(models.Model):

    class Meta:
        db_table = &#39;question&#39;
        verbose_name = &#39;Вопрос к телефону&#39;
        verbose_name_plural = &#39;Вопросы к телефону&#39;

 
    items_buy = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
    titles= models.CharField(max_length=150,verbose_name=&#39;Заголовок вопросa&#39;)
    question_text =models.TextField(max_length=100, verbose_name=&#39;Заголовок вопросa text&#39;)
    #max_prise_qustion = models.FloatField(verbose_name=&#39;Максимальная цена&#39;)

   
    def __str__(self):
           return self.titles


class Choice(models.Model):

    class Meta:
        db_table = &#39;choice&#39;
        verbose_name = &#39;Выбор ответа&#39;
        verbose_name_plural = &#39;Выбор ответов&#39;
    
    question = models.ForeignKey(Question, on_delete=models.RESTRICT,related_name=&quot;options&quot;)
    title = models.CharField(max_length=1000, verbose_name=&#39;Заголовок выбора&#39;)
    price_question = models.FloatField(verbose_name=&#39;Цена ответа&#39;)
    #lock_other = models.BooleanField(default=False, verbose_name=&#39;Смотреть другой вариант ответа&#39;)

    def __str__(self):
        return str(self.price_question)

class Answer(models.Model):
    class Meta:
        db_table = &#39;answer&#39;
        verbose_name = &#39;Ответ на вопрос&#39;
        verbose_name_plural = &#39;Ответы на вопросы&#39;

    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(&quot;question_id&quot;, &quot;choice_id&quot;)
        }
        for question in questions:
            self.fields[&quot;question_%s&quot; % question.id] = forms.ChoiceField(
                help_text=mark_safe(question.titles),
                label=mark_safe(question.question_text),
                choices=question.options.all().values_list(&quot;id&quot;, &quot;title&quot;),
                widget=forms.RadioSelect(attrs={&quot;class&quot;: &quot;form-check-input&quot;}),
            )
            self.fields[&quot;question_%s&quot; % 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(&quot;question_&quot;):
                question_id = field.split(&quot;_&quot;)[-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(&quot;choice__price_question&quot;))[&quot;total_score&quot;]
    form = AnswersForm(request.POST or None, instance=iphone)
    if form.is_valid():
        form.save() 
    return render(request, &quot;getqestionses.html&quot;, {&#39;form&#39;: form, &#39;total_score&#39;:total_score, &#39;iphone&#39;:iphone})

my HTML:

&lt;!DOCTYPE html&gt;
{% load static %}
{% load widget_tweaks %}
{% block content %}
&lt;head&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;{% static &#39;css/qestionses.css&#39; %}&quot; type=&quot;text/css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
  {% include &#39;navbar.html&#39; %}
  &lt;div class=&quot;div&quot;&gt;
     &lt;h1&gt;{{ iphones.model_produkt }}&lt;/h1&gt;  
    &lt;form method=&quot;post&quot;&gt;
        &lt;div class=&quot;ded&quot;&gt;
          {% csrf_token %}
          {% for field in form %}
          &lt;div class=&quot;qestion&quot;&gt;
            {{ field.label_tag}}
          &lt;/div&gt;
          &lt;div class=&quot;help_text&quot;&gt;
          {{ field.help_text }}
          &lt;/div&gt;
          &lt;div class=&quot;form-check&quot;&gt;
            {% for radio in field %}
            {{ radio.tag }}
            &lt;div class=&quot;chack-button&quot;&gt;
            {{ radio.choice_label }}
            &lt;/div&gt;
            {% endfor %}
        &lt;/div&gt;
      {% endfor %}
      &lt;button type=&quot;submit&quot; class=&quot;button&quot;&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  &lt;/div&gt;  
    &lt;div class=&quot;next-block&quot;&gt;
      &lt;h1&gt; {{ total_score }} &lt;/h1&gt;
      &lt;form action=&quot;{% url &#39;orderforsel&#39; iphone.id %}&quot;&gt; 
        &lt;button class=&quot;button-next-block&quot;&gt;next page for order create&lt;/button&gt;
      &lt;/form&gt;
      &lt;/div&gt;
  &lt;/div&gt;  
  &lt;script&gt;
    const submitButton = document.querySelector(&#39;.button&#39;);
    const nextBlock = document.querySelector(&#39;.next-block&#39;);
    
    nextBlock.style.display = &#39;none&#39;; // hide the next-block div initially
    
    submitButton.addEventListener(&#39;click&#39;, (event) =&gt; {
      event.preventDefault(); // prevent the form from submitting
      
      // Simulate a double click by waiting for a short delay before displaying the next-block div
      setTimeout(() =&gt; {
        nextBlock.style.display = &#39;block&#39;;
        submitButton.style.display = &#39;none&#39;;
      }, 200);
    });
  &lt;/script&gt;
&lt;/body&gt;
{% include &#39;info.html&#39; %}
{% include &#39;end_navbar.html&#39; %}
{% 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

huangapple
  • 本文由 发表于 2023年3月7日 04:01:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定