只需点击两下Submit Django即可提交表单

yruzcnhs  于 2023-03-09  发布在  Go
关注(0)|答案(1)|浏览(124)

我创建了一个页面的问题,以电话,我需要的时候,当一个人点击提交表格,他必须提交的形式与一次点击,并改变了同样的形式与一次点击太多。
但现在,只需要点击两下鼠标就可以完成。
我的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)

我的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)

我的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})

我的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 %}

我试着添加一个脚本,以获得2点击在一次点击,但不幸的是,这并没有改变我的问题。

e5nqia27

e5nqia271#

其实没必要这么复杂,Javascript有一个dblclick事件。
https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event
这将允许您轻松捕获双击

相关问题