首页 > 解决方案 > pass parameter to form from template in Django 2

问题描述

in Django I make a form which get an email address and save it in database and this my form.py:

class NewsletterUserSignUpForm(forms.ModelForm):
    class Meta:
        model = NewsletterUsers
        fields = ['email']

    def clean_email(self):
        email = self.cleaned_data.get('email')

        return email

and this is my views.py :

def newsletter_signup(request):
    form = NewsletterUserSignUpForm(request.POST or None)

    if form.is_valid():
        instance = form.save(commit=False)
        if NewsletterUsers.objects.filter(email=instance.email).exists():
            messages.warning(request, 'Your Email Already Exist In Our DataBase.',
                             'alert alert-warning alert-dismissible')
        else:
            instance.save()
            messages.success(request, 'Your Has Been Submitted To Our DataBase.',
                             'alert alert-success alert-dismissible')

    context = {
        'form': form,
    }
    return render(request, 'newsletter/subscribe.html', context)

the problem is here that this form has it own input which the input must put inside it but I want to design my own template and get input in my template then pass it to this form and my question is how do I can pass inputs in my .html template file to my form?

this is my html file and don't know to put what in href for input tag :

<form method="post" class="login100-form validate-form">
                    {% csrf_token %}
                    <span class="login100-form-title p-b-43">
                        Subscribe
                    </span>
                    <div>
                        <inputtype="email" name="Email">
                        <span class="label">Email</span>
                    </div>
                        <button type="submit" href="">
                            Subscribe
                        </button>
                    </div>

and what should I put in my href and how pass input to form from here? In addition, I'm sorry for writing mistakes in my question.

标签: djangopython-3.xdjango-modelsdjango-formsdjango-templates

解决方案


据我了解,您想创建自己的自定义输入框,并且当该框被填充时,您希望表单输入框也被填充。

使用 display:none 隐藏表单输入框。创建自己的自定义输入框,填写自定义输入框时使用javascript填充表单输入框。前任 :

<script>
   form_input_box = document.getElementById('id_of_form_input_box')
   custom_input_box = documen.getElementById('id_of_custom_input_box')

   $("id_of_custom_input_box").change(function(){
   form_input_box.value = custom_input_box.value
   });
</script>

推荐阅读