页面上的动态内容未显示

时间:2019-09-13 03:47:19

标签: javascript django django-templates

我正在尝试使用js的onclick事件在页面上生成动态内容,但是控制台中出现错误“未捕获的SyntaxError:意外的标识符”

html

{% load static %}
<head>
      <script type="text/javascript">
      function myFunction() {
        // document.getElementById("demo").innerHTML = "Paragraph changed.";
        document.getElementById("demo").innerHTML = "{{ Malegender }}";
      }
      </script>
  </head>

  <body>
    <div class="container mt-5">
<h1>Gender</h1>
      <hr>
      <h5>{{ mygender.as_p }}</h5>
      <h1 id="demo">Hello</h1>
      <div class="container">
        <button type="submit" name="gender_submit" class="btn btn-success" onclick="myFunction()">Confirm</button>
      </div>
    </div>
  </body>

views.py

def Gender(request):
    gender_selection = GenderForm()
    male_detail = MaleForm()
    Male = False
    print("Value of male",Male)
    if 'gender_submit' in request.POST:
        male_detail = MaleForm(data=request.POST)
        Male = True
        print("Value of male d",Male)

    print("Value of male a",Male)
    return render(request, 'Gender.html',{"mygender":gender_selection,"Malegender":male_detail})

forms.py

class MaleForm(forms.ModelForm):
    class Meta:
        model = GenderModel
        fields = ('genderMale','genderMale1','genderMale2','genderMale3','genderMale4')

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.

class GenderModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    gender_choice=(('Male','Male'),('Female','Female'),)
    gender = models.CharField(max_length=6,choices=gender_choice,null=True,)
    genderMale = models.BooleanField(default=False)
    genderMale1 = models.BooleanField(default=False)
    genderMale2 = models.BooleanField(default=False)
    genderMale3 = models.BooleanField(default=False)
    genderMale4 = models.BooleanField(default=False)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        GenderModel.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.gendermodel.save()

当我单击按钮时,控制台上显示错误。我正在尝试在用户单击按钮时显示该内容

1 个答案:

答案 0 :(得分:0)

this问题使用onclick属性建议从不。相反,您可以尝试使用如下事件监听器:

<button type="submit" name="gender_submit" class="btn btn-success"
id="gender_submit_button">Confirm</button>

<script type="text/javascript">
function myFunction() {
  document.getElementById("demo").innerHTML = "{{ Malegender }}";
}

document.getElementById('gender_submit_button').addEventListener('click', myFunction);
</script>

此外,请确保将脚本放置在按钮和演示的 之后。