【问题标题】:Subscription form with Django and jQuery使用 Django 和 jQuery 的订阅表单
【发布时间】:2016-01-05 06:49:01
【问题描述】:

我一直在做这个页面,可以在其中订阅该站点,并且我一直在尝试在 Django 模板中使用 jQuery 触发表单。 现在,如果用户想订阅,注册页面会正确打开,如果一切正常,注册会顺利进行,然后会返回可以登录的主页;如果出现错误(错误的用户名或电子邮件或密码),它会返回主页而不指出任何错误 - 只有当您再次点击打开注册表时才会显示错误。

我将复制粘贴我的代码。

  • 主页.html

	{% if user.is_authenticated %}
	<h2>Welcome back, {{ user.username }}. Let's explore the World together!</h2>
	{% else %}
	
  <!-- Trigger the modal with a button -->
  <h2><button id="myBtn">Subscribe now :)</a></h2>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h3 class="modal-title">Register with Tent a garden</h3>
        </div>
        <div class="modal-body">
        {% if registered %}
        
			<h4>Tent a garden says: <strong>thank you for registering!</strong></h4>
			<a href="/">Return to the homepage.</a><br />
			{% else %}
			<h4>Tent a garden says: <strong>register here!</strong></h4><br />
			
			<form id="user_form" method="post" action="" enctype="multipart/form-data">
			
				{% csrf_token %}
				
				{{ user_form.as_p }}
				{{ profile_form.as_p }}
				
				<input type="submit" class="btn btn-info" name="submit" value="Register" />
			</form>
        {% endif %}
        </div>
        <div class="modal-footer">
			<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    
    </div>
    </div>
    </div>
    
    <script>
		$(document).ready(function(){
			$("#myBtn").click(function(){
				$("#myModal").modal();
			});
		});
	</script>
  
	<h2>Are you already a member? Then, <a href="/login/">login</a>!</h2>
	{% endif %}
  • views.py

    from django.shortcuts import render_to_response, render, redirect
    from django.template import RequestContext
    from django.http import HttpResponseRedirect, HttpResponse
    from django.core.urlresolvers import reverse
    from django.contrib.auth import authenticate, login, logout
    from django.contrib.auth.decorators import login_required
    
    from tentagarden.forms import UserForm, UserProfileForm
    
    def home(request):
        context = RequestContext(request)
    
        registered = False
    
        if request.method == 'POST':
            user_form = UserForm(data=request.POST)
            profile_form = UserProfileForm(data=request.POST)
    
            if user_form.is_valid() and profile_form.is_valid():
                user = user_form.save()
    
                user.set_password(user.password)
                user.save()
    
                profile = profile_form.save(commit=False)
                profile.user = user
    
                if 'picture' in request.FILES:
                    profile.picture = request.FILES['picture']
    
                profile.save()
    
                registered = True
    
            else:
                print user_form.errors, profile_form.errors
    
        else:
            user_form = UserForm()
            profile_form = UserProfileForm()
    
        return render_to_response(
                'tentagarden/home.html',
                {'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
                context)
    
  • forms.py

    from django import forms
    from django.forms import ModelForm
    from tentagarden.models import UserProfile
    from django.contrib.auth.models import User
    
    class UserForm(forms.ModelForm):
        password = forms.CharField(widget=forms.PasswordInput())
    
        class Meta:
            model = User
            fields = ('username', 'email', 'password')
    
    class UserProfileForm(forms.ModelForm):
        class Meta:
            model = UserProfile
            fields = ('website', 'picture')
    
  • models.py

    from django.db import models
    from django.utils import timezone
    from autoslug import AutoSlugField
    from django.contrib.auth.models import User
    
    class UserProfile(models.Model):
        user = models.OneToOneField(User)
        website = models.URLField(blank=True)
        picture = models.ImageField(upload_to='profile_images', blank=True)
    
        def __unicode__(self):
            return self.user.username
    
  • urls.py

    from django.conf.urls import patterns, url
    
    urlpatterns = patterns('tentagarden.views',
        url(r'^$', 'home', name='home'),
        url(r'^list/$', 'list', name='list'),
        url(r'^login/$', 'user_login', name='login'),
        url(r'^logout/$', 'user_logout', name='logout'),
    )
    

我错过了什么?

谢谢!

【问题讨论】:

  • 您希望这部分的哪一部分表现得不同?如果表单出现错误,您是否希望模态框自动弹出?

标签: jquery python html django forms


【解决方案1】:

您的表单错误未显示,因为该表单仅在用户单击按钮时显示。

<script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            // You need to be triggering this when there was an error
            $("#myModal").modal();
        });
    });
</script>

一个简单的补丁修复是将一个额外的上下文变量传递给模板。类似registration_failed = TrueFalse

然后像这样修改你的代码:

# in views.py
else:
    print user_form.errors, profile_form.errors
    return render_to_response(
        'tentagarden/home.html',
        {'user_form': user_form, 'profile_form': profile_form, 'registered': registered, 'registration_failed': True},
        context)

还有:

<!-- in your HTML -->
<script>
    $(document).ready(function(){
        $("#myBtn").click(function(){
            $("#myModal").modal();
        });
        // If the template is rendered with registration_failed == true
        // Then send a click to the button controlling the modal.
        if ({{registration_failed}}) {
            $("#myBtn").click();
        }
    });
</script>

请注意,这不是解决您问题的最佳长期解决方案,我认为您需要大量重构代码。但这将解决眼前的问题。

【讨论】:

  • 最好的方法是什么?我的意思是,我并不是要你为我做所有事情,但如果你能告诉我一些特定的练习,我将不胜感激:)
  • 我会使用 javascript 客户端验证方法,这样您就不必让用户发布整个表单并重新加载页面只是说某些内容没有正确输入。谷歌javascript form validation,看看你能找到什么。
  • 谢谢,我去看看!
  • 仅在客户端控制验证是否是一种好习惯?
  • 不,你绝对应该两边都做。最低限度,仅限服务器端。在您的特定情况下,用户可以方便地在客户端进行验证。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 2014-02-19
  • 1970-01-01
相关资源
最近更新 更多