Django Python表单不会呈现

时间:2015-08-11 04:53:23

标签: python django django-forms django-templates django-views

我有一个项目要求我在forms.py,views.py和新模板上创建新语法。 Django运行整个代码而没有检测到任何错误,但每次我去模板时表单都不会呈现。

forms.py

class Email_SignIn_Form(forms.Form):
      username= forms.CharField(max_length=30)
      email = forms.EmailField(initial='Your Email...')
      country_code=forms.CharField(max_length=5, initial='65')
      country_code=forms.CharField(max_length=5, initial='65')
      cellphone=forms.CharField(max_length=15, help_text='only numbers')
      opt_in = forms.BooleanField(initial=True, required=False)

views.py(它已经缩进)

def sign_in_email(request, template_name):
    if request.method == 'POST':
    next = request.GET.get('next')
    add_as_portal_member = request.GET.get('add_to_member')
    if next is None:
       next = '/'
    email_signin_form = Email_SignIn_Form(request.POST)
if email_signin_form.is_valid():
    email = email_signin_form.cleaned_data['email']
    name = email
    country_code = ''
    cell_phone = ''

else:
    return render_to_response(template_name, locals(), context_instance=RequestContext(request))

    if email_signin_form:
        opt_in = True
    else:
        opt_in = email_signin_form.cleaned_data['opt_in']

        if opt_in:
            username_error=''
            #check for exiting email
            user = User.objects.filter(email=email)

            if user.exists():
                print "Email already exist in registered user"
                username_error = 'Your particulars have been recorded, but you are already registered as members.'
                return render_to_response("/account/thankyou/?next=%s",locals(), context_instance=RequestContext(request))

            else:
                try:
                    #check for duplicate username
                    User.objects.get(username=email)

                    username_error = 'Your particulars have been recorded, but you are already registered as members.'
                    return render_to_response("/account/thankyou/?next=%s",locals(), context_instance=RequestContext(request))
                except:
                    #initial creation of user object
                    try:
                        #create random password
                        import os, random, string

                        length = 13
                        chars = string.ascii_letters + string.digits + '!@$()'
                        random.seed = (os.urandom(1024))
                        password = ''.join(random.choice(chars) for i in range(length))

                        User.objects.create_user(email,
                                                 email,
                                                 password,
                                                )
                        user = User.objects.get(username=email)
                        user_profile=UserProfile(user=user, cellphone=cell_phone, country_prefix=country_code)
                        user_profile.save()

                        print ("User created")

                        #send email to user
                        try:
                            admin_email = settings.EMAIL_ORIGIN_MEMBERS
                            email_txt = loader.get_template('account/emails/createaccount.html')
                            email_html = loader.get_template('account/emails/createaccounthtml.html')
                            email_context = Context({'u_name': email,
                                                     'username': email,
                                                     'password': password,
                                                    })
                            new_user_mail = EmailMultiAlternatives('Welcome',
                                                                   email_txt.render(email_context),
                                                                   admin_email,
                                                                   [user.email, ],
                                                                   headers={'Reply-To': 'admin@admin.com'}
                            )
                            new_user_mail.attach_alternative(email_html.render(email_context), 'text/html')
                            new_user_mail.send()
                        except:
                            print ("cannot send email")

                        if landing.redirect_after_signup:
                            print ("Redirect after signup")
                            return render_to_response("/account/thankyou/?next=%s",locals(), context_instance=RequestContext(request))
                        #else:
                            #return redirect(landing.link)

                    except:
                        print ("entered except block")
                        pass

        else:
            if landing.link != '':
                return render_to_response("/account/thankyou/?next=%s",locals(), context_instance=RequestContext(request))
            else:
                return render_to_response(template_name, locals(), context_instance=RequestContext(request))

else:
    email_only_form = Email_Only_Form()

return render_to_response(template_name, locals(), context_instance=RequestContext(request))

sign_in_email.html

    {% extends "index.html" %}

{% block heroslider %}
    <div class="page_title2" style="padding:150px 0px 50px 0px;">
        <div class="container">

            <h1>User Registration</h1>

        </div>
    </div><!-- end page title -->
{% endblock %}

{% block main_body %}
<style type="text/css">
    input[type='radio'], input[type='checkbox'] {
        width:20px;
        vertical-align: middle;
    }

    div.reg_error {
        position:relative;
        top:-10px;
        margin-top:0px;
        padding-top:0px;
        color:red;
    }
</style>

<div class="container">
    <form class="pagesignup logiform" action="" method="POST">{% csrf_token %}
        <div class="row">
            <div class="large-12 columns" style="margin-bottom: 30px;">
                <div class="reg_form">
                    <div class="sky-form">
                        <header>REGISTER</header>
                    </div>
                    <div class="row">
                        <div class="large-12 columns">
                            <p>Email<br/>
                                {{email_signin_form.email}}
                            <div class="reg_error">{{ email_signin_form.email.errors.as_text }}</div></p>     
                        </div>
                    </div>
                    <div class="row">
                        <div class="large-12 large-centered columns" style="text-align:center;padding:20px;">
                            <div>{{ email_signin_form.opt_in }} Yes - send me CoAssets newsletter and partners deals.</div><br/>
                            <div><input class="but_medium1" style="border:none;" type = "submit" value="REGISTER" /></div><br/>
                            <div>By clicking on register, you have read and agreed to our <a href="/terms-of-use/">terms of use</a>.</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<!-- Google Code for Sign Up Page (landed) Conversion Page -->
<script type="text/javascript">
    /* <![CDATA[ */
    var google_conversion_id = 969557266;
    var google_conversion_language = "en";
    var google_conversion_format = "3";
    var google_conversion_color = "ffffff";
    var google_conversion_label = "5zU4CJby_FoQkoqpzgM";
    var google_remarketing_only = false;
    /* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
    <div style="display:inline;">
    <img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/969557266/?label=5zU4CJby_FoQkoqpzgM&amp;guid=ON&amp;script=0"/>
    </div>
</noscript>

<script>
    var $=jQuery.noConflict();
    $(document).ready(function(){
        var choice = $('#id_user_type').val();

        if (choice == 'INV') {
            $('#common-info').css('display', 'none');
            $('#agent-info').css('display', 'none');
            $('#ai-info').css('display','none');

        } else if (choice == 'FND' || choice == 'DEV') {
            $('#common-info').css('display', '');
            $('#agent-info').css('display', 'none');
            $('#ai-info').css('display','none');

        } else if (choice == 'AGT') {
            $('#common-info').css('display', '');
            $('#agent-info').css('display', '');
            $('#ai-info').css('display','none');
        } else if (choice=='HNW') {
            $('#common-info').css('display', 'none');
            $('#agent-info').css('display', 'none');
            $('#ai-info').css('display','');
        }
    });
    $('#id_user_type').change(function() {
        var choice = $(this).val();

        if (choice == 'INV') {
            $('#common-info').css('display', 'none');
            $('#agent-info').css('display', 'none');
            $('#ai-info').css('display','none');

        } else if (choice == 'FND' || choice == 'DEV') {
            $('#common-info').css('display', '');
            $('#agent-info').css('display', 'none');
            $('#ai-info').css('display','none');

        } else if (choice == 'AGT') {
            $('#common-info').css('display', '');
            $('#agent-info').css('display', '');
            $('#ai-info').css('display','none');
        } else if (choice=='HNW') {
            $('#common-info').css('display', 'none');
            $('#agent-info').css('display', 'none');
            $('#ai-info').css('display','');
        }
    });

  $(function() {
    var names = {{ org_list|escape|safe }};

    var accentMap = {
      "á": "a",
      "ö": "o"
    };
    var normalize = function( term ) {
      var ret = "";
      for ( var i = 0; i < term.length; i++ ) {
        ret += accentMap[ term.charAt(i) ] || term.charAt(i);
      }
      return ret;
    };

    $( "#id_company_name" ).autocomplete({
      source: function( request, response ) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
        response( $.grep( names, function( value ) {
          value = value.label || value.value || value;
          return matcher.test( value ) || matcher.test( normalize( value ) );
        }) );
      }
    });
  });
  </script>
{% endblock %}
enter code here

1 个答案:

答案 0 :(得分:0)

首先,您需要在视图中指定表单:

email_signing_form = MyForm # Your form which you want to render.

其次,您需要在上下文中传递此表单以在模板中呈现

return render_to_response("your.html", {"email_signing_form":email_signing_form}, context_instance=RequestContext(request))